package com.info.zhiduoduo.admin.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.info.zhiduoduo.admin.model.formbean.account.CheckSameLabelCompanyBean;
import com.info.zhiduoduo.admin.model.formbean.account.GetAnEnterpriseContractBean;
import com.info.zhiduoduo.admin.model.formbean.company.*;
import com.info.zhiduoduo.admin.model.formbean.crm.UpdateIncomingFormBean;
import com.info.zhiduoduo.admin.model.formbean.system.LoginFormBean;
import com.info.zhiduoduo.admin.model.vo.company.SameLabelVO;
import com.info.zhiduoduo.common.configs.*;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.company.CompanyAccountFlowAccountType;
import com.info.zhiduoduo.common.constants.company.CompanyAccountFlowBizType;
import com.info.zhiduoduo.common.constants.company.CompanyPayType;
import com.info.zhiduoduo.common.constants.company.CompanyTransferMakerGrouponState;
import com.info.zhiduoduo.common.constants.pay.PayTypeSn;
import com.info.zhiduoduo.common.excelconverter.ZddReadListener;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.exception.RollbackException;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.*;
import com.info.zhiduoduo.core.formbean.mqproducer.Producer;
import com.info.zhiduoduo.core.service.CommonService;
import com.info.zhiduoduo.core.service.CoreCompanyService;
import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.WxPartnerMessageService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.service.common.RedisService;
import com.info.zhiduoduo.core.service.impl.CeoNoticeService;
import com.info.zhiduoduo.core.service.payment.thirdpay.ZhaoShangTradeBulterService;
import com.info.zhiduoduo.repository.dto.company.*;
import com.info.zhiduoduo.repository.dto.crm.InfoIncomingDto;
import com.info.zhiduoduo.repository.dto.crm.ProductEntrustPriceFormBean;
import com.info.zhiduoduo.repository.dto.partner.PartnerAndCompanyRelationshipDto;
import com.info.zhiduoduo.repository.entity.company.*;
import com.info.zhiduoduo.repository.dto.project.ProjectCompanyDto;
import com.info.zhiduoduo.repository.entity.company.Company;
import com.info.zhiduoduo.repository.entity.company.CompanyAccount;
import com.info.zhiduoduo.repository.entity.company.CompanyAccountflow;
import com.info.zhiduoduo.repository.entity.company.CompanyAuthRecord;
import com.info.zhiduoduo.repository.entity.company.CompanyEntrustFile;
import com.info.zhiduoduo.repository.entity.company.CompanyEntrustFileNotification;
import com.info.zhiduoduo.repository.entity.company.CompanyProject;
import com.info.zhiduoduo.repository.entity.company.CompanyTransferMakerGroupon;
import com.info.zhiduoduo.repository.entity.company.ComplianceIntelligence;
import com.info.zhiduoduo.repository.entity.company.EnterpriseScore;
import com.info.zhiduoduo.repository.entity.crm.ChangeRecord;
import com.info.zhiduoduo.repository.entity.crm.CrmCustomer;
import com.info.zhiduoduo.repository.entity.crm.CrmSystemManager;
import com.info.zhiduoduo.repository.entity.crm.Incoming;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceProject;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.entity.marketingcooperative.MarketingCooperativeCompanyForm;
import com.info.zhiduoduo.repository.entity.marketingcooperative.MarketingCooperativeCompanyFormItem;
import com.info.zhiduoduo.repository.entity.partner.Partner;
import com.info.zhiduoduo.repository.entity.partner.PartnerAccount;
import com.info.zhiduoduo.repository.entity.partner.PartnerRecommendCompany;
import com.info.zhiduoduo.repository.entity.quota.CityConfig;
import com.info.zhiduoduo.repository.entity.system.AccountLinkLabel;
import com.info.zhiduoduo.repository.entity.system.BusinessManager;
import com.info.zhiduoduo.repository.mapper.company.*;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;

import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerCompanyMapper;
import com.info.zhiduoduo.repository.mapper.quota.CompanyQuotaMapper;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional
public class CompanyService extends BaseService {

	@Autowired
	RedisService redisService;
	@Autowired
	WxMessageService wxMessageService;
	@Autowired
	WxPartnerMessageService wxPartnerMessageService;
	@Autowired
	CeoNoticeService ceoNoticeService;
	@Autowired
	CommonService commonService;
	@Autowired
	ZhaoShangTradeBulterService zhaoShangTradeBulterService;

	@Resource
	CompanyMapper companyMapper;
	@Resource
	CompanyAccountMapper companyAccountMapper;
	@Resource
	CompanyProjectMapper companyProjectMapper;
	@Resource
	CrowdsourceProjectMapper crowdsourceProjectMapper;
	@Resource
	CompanyTransferMakerGrouponMapper companyTransferMakerGrouponMapper;
	@Resource
	CompanyEntrustFileMapper companyEntrustFileMapper;
	@Resource
	CoreCompanyService coreCompanyService;
	@Resource
	CompanyEntrustFileNotificationMapper companyEntrustFileNotificationMapper;
	@Resource
	EnterpriseScoreMapper enterpriseScoreMapper;
	@Resource
	CompanyZhaoshangSubLedgerMapper companyZhaoshangSubLedgerMapper;
	@Resource
	CompanyZhaoshangSubLedgerRechargeMapper companyZhaoshangSubLedgerRechargeMapper;
	@Resource
	CompanyZhaoshangSubLedgerIncomingRecordMapper companyZhaoshangSubLedgerIncomingRecordMapper;
	@Resource
	ComplianceIntelligenceMapper complianceIntelligenceMapper;
	@Resource
	CompanyPaymentMapper companyPaymentMapper;
	@Resource
	CompanyPartyMapper companyPartyMapper;
	@Resource
	CompanyTaxMapper companyTaxMapper;
	@Resource
	CompanyQuotaMapper companyQuotaMapper;
	@Resource
	MakerStudioMapper makerStudioMapper;
	@Resource
	PartnerCompanyMapper partnerCompanyMapper;

	@Autowired
	RechargeNotifyConfig rechargeNotifyConfig;
	@Autowired
	PayConfig payConfig;
	@Autowired
	ZddUrlConfig zddUrlConfig;
	@Autowired
	KltPayConfig kltPayConfig;
	@Autowired
	NotificationConfig notificationConfig;

	@Autowired
	Producer producer;

	public SmartResult login(BaseSimpleFormBean<LoginFormBean> formBean) {
		LoginFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();
		String phone = reqdata.getLoginname();
		String password = reqdata.getPassword();

		if (StringUtil.isAnyEmpty(phone, password)) return smartResult(StatusMsg.StatusMsg_124);

		Company company = companyMapper.checkCompanyExistByPhone(phone);

		if (null == company) {
			return smartResult(StatusMsg.StatusMsg_302);
		}

		String md5Pwd = MD5Util.md5(password + company.getSalt());
		if (!md5Pwd.equals(company.getPassword())) {
			return smartResult(StatusMsg.StatusMsg_123);
		}

		CompanyBriefDto dto = new CompanyBriefDto();
		BeanUtils.copyProperties(company, dto);
		return smartResult(dto);
	}

	@Transactional
	public SmartResult companySetting(Integer compid, CompanySetting setting) {
		// 校验企业信息
		Company company = new Company().selectById(compid);
		Asserts.notNull(company);
		CompanyAccount companyAccount = companyAccountMapper.getByCompid(compid);
		Asserts.notNull(companyAccount);

		String module = setting.getModule();

		switch (module){
			case "base":
				CompanySetting.BaseModule baseModule = setting.getBaseModule();
				Asserts.notNull(baseModule);
				updateCompanyInfo(compid,companyAccount.getAcctid(),baseModule);
				break;
			case Constants.BUSINESS_SN_ZDD:
				CompanySetting.BusinessZddModule zddModule = setting.getBusinessZddModule();
				Asserts.notNull(zddModule);
				updateCompanyInfo(compid,companyAccount.getAcctid(),zddModule);

				saveCompanyParty(compid, Constants.BUSINESS_SN_ZDD, zddModule.getCompanyPartyList());
				break;
			case Constants.BUSINESS_SN_CRO:
				CompanySetting.BusinessCroModule croModule = setting.getBusinessCroModule();
				Asserts.notNull(croModule);
				updateCompanyInfo(compid,companyAccount.getAcctid(),croModule);

				saveCompanyParty(compid, Constants.BUSINESS_SN_CRO, croModule.getCompanyPartyList());
				break;
			case Constants.BUSINESS_SN_ODD:
				CompanySetting.BusinessOddModule oddModule = setting.getBusinessOddModule();
				Asserts.notNull(oddModule);
				updateCompanyInfo(compid,companyAccount.getAcctid(),oddModule);

				saveCompanyParty(compid, Constants.BUSINESS_SN_ODD, oddModule.getCompanyPartyList());
				break;
			case Constants.BUSINESS_SN_GROUP:
				CompanySetting.BusinessGroupModule groupModule = setting.getBusinessGroupModule();
				updateCompanyInfo(compid,companyAccount.getAcctid(),groupModule);

				saveCompanyParty(compid, Constants.BUSINESS_SN_GROUP, Collections.singletonList(groupModule.getCompanyParty()));
				break;
			default:
				return SmartResult.fail(StatusMsg.StatusMsg_101);
		}
		// 检查企业当下支付方式，如果有招商银行，检查是否创建了记账子单元
		//委托发单支付失败 通知riley,项目支付失败 通知给riley
		new Thread(() -> {
			List<CompanyPayment> payList = companyPaymentMapper.getCompanyPayList(compid);
			for (CompanyPayment payment : payList) {
				if (payment.getSourceId() != null && PayTypeSn.ZS.equals(payment.getPayTypeSn())) {
					// 新建记账子单元
					zhaoShangTradeBulterService.createSubLedgerIfNotExist(company, payment.getSourceId());
				}
			}
		}).start();
		return smartResult();
	}

	// 修改企业基础信息
	public void updateCompanyInfo(Integer compid, Integer acctid, Object object) {
		Company updateCompany = new Company();
		BeanUtils.copyProperties(object, updateCompany);

		CompanyAccount updateAccount = new CompanyAccount();
		BeanUtils.copyProperties(object, updateAccount);

		if (!ReflectionUtil.checkObjAllFieldsIsNull(updateCompany)) {
			updateCompany.setCompid(compid).updateById();
		}
		if (!ReflectionUtil.checkObjAllFieldsIsNull(updateAccount)) {
			updateAccount.setAcctid(acctid).updateById();
		}
	}

	// 修改企业运营主体集合
	public void saveCompanyParty(Integer compid, String businessSn, List<CompanyParty> partyList) {

		// 去重判断 判断支付方式是否有重复
		List<Integer> sameList = partyList.stream().collect(Collectors.toMap(CompanyParty::getPayId, e -> 1, Integer::sum)).entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());
		if(!CollectionUtils.isEmpty(sameList)){
			throw new SmartException(StatusMsg.StatusMsg_380);
		}

		// 获取历史主体配置
		List<CompanyParty> companyPartyList = companyPartyMapper.getCompanyPartyList(compid, businessSn);
		if (!CollectionUtils.isEmpty(companyPartyList)) {
			// 获取新id集合
			Set<Integer> newIds = partyList.stream().map(CompanyParty::getId).filter(Objects::nonNull).collect(Collectors.toSet());
			List<Integer> delIds = companyPartyList.stream().map(CompanyParty::getId).filter(integer -> !newIds.contains(integer)).collect(Collectors.toList());
			// 删除历史数据
			delIds.forEach(t -> companyPartyMapper.deleteById(t));
		}

		// 遍历新的数据集合 执行修改/新增
		for (CompanyParty pay : partyList) {
			CompanyParty companyParty = new CompanyParty();
			BeanUtils.copyProperties(pay, companyParty);
			companyParty.setDeleted(0);
			companyParty.setBusinessSn(businessSn);
			companyParty.setCompid(compid);
			companyParty.setUpdatedTime(new Date());
			companyParty.insertOrUpdate();
		}
		// 获取企业所有支付方式，初始化新增的支付方式余额为0
		Set<Integer> newPayIds = partyList.stream().map(CompanyParty::getPayId).filter(Objects::nonNull).collect(Collectors.toSet());
		for (Integer payId : newPayIds) {
			CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(compid, payId);
			if (companyPayment == null) {
				new CompanyPayment().setCompid(compid).setPayId(payId).insert();
			}
		}
	}

	public SmartResult getSetting(Integer compid){
		// 校验企业信息
		Company company = new Company().selectById(compid);
		Asserts.notNull(company);
		CompanyAccount companyAccount = companyAccountMapper.getByCompid(compid);
		Asserts.notNull(companyAccount);

		// 设置基础信息
		CompanySetting companySetting = new CompanySetting().format(companyAccount,company);

		// 设置企业支付方式
		List<CompanyParty> partyList = companyPartyMapper.getCompanyPartyList(compid,null);
		Map<String, List<CompanyParty>> collect = partyList.stream().collect(Collectors.groupingBy(CompanyParty::getBusinessSn));
		companySetting.getBusinessZddModule().setCompanyPartyList(collect.get(Constants.BUSINESS_SN_ZDD));
		companySetting.getBusinessCroModule().setCompanyPartyList(collect.get(Constants.BUSINESS_SN_CRO));
		companySetting.getBusinessOddModule().setCompanyPartyList(collect.get(Constants.BUSINESS_SN_ODD));
		List<CompanyParty> groupList = collect.get(Constants.BUSINESS_SN_GROUP);
		if (groupList != null && groupList.size() != 0) {
			companySetting.getBusinessGroupModule().setCompanyParty(groupList.get(0));
		}

		//  企业费率设置
		companySetting.setCompanyTaxDto(companyTaxMapper.getCompanyTaxByCompid(compid));
		// 企业限额设置
		companySetting.setCompanyQuotaDto(companyQuotaMapper.getByCompid(compid));

		return smartResult(companySetting);
	}

	public List<CompanyPayment> getCompanyPayList(Integer compid) {
		return companyPaymentMapper.getCompanyPayList(compid);
	}

	/**
	 * 获取企业认证列表
	 */
	public SmartResult getVerifyList(BaseSimpleFormBean<CompanyListFormBean> formBean) {
		CompanyListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		String name = reqdata.getName();
		int state = reqdata.getState();
		String inviter = reqdata.getInviter();
		String businessManager = reqdata.getBusinessManager();
		int crowdsource = reqdata.getCrowdsource();
		Integer strategyInvoice = reqdata.getStrategyInvoice();
		Integer quotaFlag = reqdata.getQuotaFlag();
		Integer specialRateFlag = reqdata.getSpecialRateFlag();
		Integer activeRegister = reqdata.getActiveRegister();
		Integer controlFill = reqdata.getControlFill();
		Integer standard = reqdata.getStandard();
		Integer friendlyState = reqdata.getFriendlyState();
		Integer merchandiserId = reqdata.getMerchandiserId();
		Integer agentOperationAccount = reqdata.getAgentOperationAccount();
		Integer entrustFileStates = reqdata.getEntrustFileState();
		Integer marketingCooperative = reqdata.getMarketingCooperative();
		if (startDate == null) startDate = new Date(0);
		if (endDate == null) endDate = new Date();
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CompanyVerifyBriefDto> list = companyMapper.getCompanyList(name,reqdata.getCompid(), inviter, businessManager, state, crowdsource,
				strategyInvoice,
				startDate, endDate, specialRateFlag, activeRegister, controlFill, quotaFlag, standard, friendlyState,
				merchandiserId, agentOperationAccount, entrustFileStates,reqdata.getRegPhone(),marketingCooperative, reqdata.getTradeFlag(), reqdata.getAccountLinkIds());
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 获取实名审核详情
	 * 参数: acctid
	 */
	public SmartResult getAccountDetail(BaseSimpleFormBean<Integer> formBean) {
		Integer acctid = formBean.getReqdata();
		if (acctid == null || acctid <= 0) return errorParamSmartResult();

		AccountDetail detail = companyAccountMapper.getAccountDetail(acctid);
		return smartResult(detail);
	}

	/**
	 * 获取企业所有详细资料
	 */
	public SmartResult<CompanyDetailDto> getCompanyAllInfo(BaseSimpleFormBean<Integer> formBean) {

		Integer compid = formBean.getReqdata();
		if (compid == null || compid <= 0) return errorParamSmartResult();

		return smartResult(getCompanyInfo(compid));
	}

	public CompanyDetailDto getCompanyInfo(Integer compid) {
		if (compid == null) return null;

		return companyMapper.getCompanyInfo(compid);
	}

	/**
	 * 实名审核企业,通过或驳回
	 */
	public SmartResult verifyCompany(BaseSimpleFormBean<VerifyCompanyFormBean> formBean) {
		VerifyCompanyFormBean reqdata = formBean.getReqdata();
		int adminid = formBean.getUserid();
		if (reqdata == null) return errorParamSmartResult();

		int compid = reqdata.getCompid();
		int acctid = reqdata.getAcctid();
		int state = reqdata.getState();
		Integer partyId = reqdata.getPartyId();
		String reason = reqdata.getReason();
		String remark = reqdata.getRemark();
		Integer economyCategoryId = reqdata.getEconomyCategoryId();

		Company company = new Company().selectById(compid);
		if (company == null) {
			return smartResult(StatusMsg.StatusMsg_302);
		} else if (company.getState() == Constants.comp_state_4) {
			return smartResult(StatusMsg.StatusMsg_306);
		}

		CompanyAccount companyAccount = new CompanyAccount().selectById(acctid);
		if (companyAccount == null) {
			return smartResult(StatusMsg.StatusMsg_302);
		} else if (companyAccount.getRealnameAuth() == Constants.comp_auth_2) {
			return smartResult(StatusMsg.StatusMsg_306);
		}

		int authState = state == 0 ? Constants.comp_state_4 : Constants.comp_state_3;
		int realnameAuth = state == 0 ? Constants.comp_auth_2 : Constants.comp_auth_1;

		// 审核通过
		if (realnameAuth == Constants.comp_auth_2) {
			companyAccount.setAuthPassTime(new Date());
			// 设置企业昵称
			String nickname = "zdd_" + MD5Util.md5(company.getCompname() + RandomUtil.generateString(8)).substring(0, 8).toLowerCase();
			company.setCompnickname(nickname);
		}

		companyAccount.setEconomyCategoryId(economyCategoryId)
				.setRealnameAuth(realnameAuth)
				.setBusinessManagerId(reqdata.getBusinessManagerId())
				.setAgreeProtocol(1);
//				.setPayType(reqdata.getPayType());
//
//		if (CompanyPayType.isZhaoShangPayType(NumberUtil.safeInt(reqdata.getPayType()))) {
//			// 如果是招商银行，新建记账子单元
//			zhaoShangTradeBulterService.createSubLedgerIfNotExist(company, reqdata.getPayType());
//		}
//		int oldPartyId = NumberUtil.safeInt(company.getPartyId());
		if (company.setState(authState).updateById() && companyAccount.updateById()) {
			//取消ceo提醒通知
			ceoNoticeService.recordCompanyVerify(compid, 1);

			//如果是审核通过，防止重复点击导致插入多条数据
			if (state == 0) {
				CompanyAuthRecord record = new CompanyAuthRecord().selectOne(
						Condition.create().eq("compid", compid).orderBy("id", false).last(" limit 1"));
				if (record != null && record.getState() == 0) {
					//上一条已经是审核通过的记录，那么就不需要再记录了。
					return smartResult();
				}
			}
			new CompanyAuthRecord().setAdminid(adminid).setCompid(compid).setState(state).setReason(reason).setRemark(remark).insert();
			//结果通知企业
			wxMessageService.compAuthState(compid);

			if (authState == Constants.comp_state_4) {
				//企业注册时填邀请码的，审核通过的时候，添加到合伙人推荐的企业待审核列表里,  并通知邀请者
				String inviteCode = company.getInviteCode();
				if (StringUtil.isNotEmpty(inviteCode)) {

					PartnerAccount account = new PartnerAccount().selectOne(
							Condition.create().eq("promo_code", inviteCode).last(" limit 1"));
					if (account != null) {
						Partner partner = new Partner().selectById(account.getPartnerid());
						new PartnerRecommendCompany().setPartnerid(partner.getPartnerid())
								.setRecommendCompany(company.getCompname())
								.setState(Constants.PARTNER_RECOMMEND_VERIFYING)
								.insert();

						wxPartnerMessageService.noticeInviteCompany(company.getCompname(), partner.getOpenid(), company.getCompid());
					}
				}

				//通知商务经理
				new Thread(() -> commonService.sendEnterpriseWeChatNotice(companyAccount.getBusinessManagerId(), company.getCompname(),
						2)).start();
			}
		} else {
			return optFailSmartResult();
		}

		return smartResult();
	}

	/**
	 * 编辑企业实名信息
	 */
	public SmartResult editCompany(BaseSimpleFormBean<EditCompanyFormBean> formBean) {

		EditCompanyFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) {
			return errorParamSmartResult();
		}

		int compid = reqdata.getCompid();
		Company company = new Company().selectById(compid);
		String companyName = company.getCompname();
		if (!companyName.equals(reqdata.getCompname())){
			Company name = new Company().selectOne(Condition.create().eq("compname", reqdata.getCompname()));
			Asserts.isNull(name, StatusMsg.StatusMsg_376);
		}
		BeanUtils.copyProperties(reqdata, company);
		company.updateById();

		CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		Asserts.notNull(account, StatusMsg.StatusMsg_302);

		// 判断是否切换支付方式. 如果切换的话, 原来的账户余额必须要清零才行.
//		Integer oldPayType = account.getPayType();
//		int newPayType = reqdata.getPayType();
//		if (newPayType != oldPayType &&
//				NumberUtil.intIn(newPayType, CompanyPayType.DAYS_JIUGE, CompanyPayType.DAYS_WUSHENG, CompanyPayType.TRANSFER_WUSHENG) &&
//				NumberUtil.intIn(oldPayType, CompanyPayType.DAYS_JIUGE, CompanyPayType.DAYS_WUSHENG, CompanyPayType.TRANSFER_WUSHENG)) {
//			Asserts.isTrue(account.getBalance().doubleValue() == 0, StatusMsg.StatusMsg_331);
//		}
//
//		// 切换了支付方式，如果是招商银行，检查是否创建了记账子单元
//		if (newPayType != oldPayType && CompanyPayType.isZhaoShangPayType(newPayType)) {
//			// 新建记账子单元
//			zhaoShangTradeBulterService.createSubLedgerIfNotExist(company, reqdata.getPayType());
//		}

		BeanUtils.copyProperties(reqdata, account);
		if (!CollectionUtils.isEmpty(reqdata.getShareholder())) {
			account.setShareholder(JSON.toJSONString(reqdata.getShareholder()));
		}
		account.update(Condition.create().eq("compid", compid));

//		// 判断修改了运营主体，发送通知
//		int newPartyId = NumberUtil.safeInt(company.getPartyId());
//		if (newPartyId > 0 && oldPartyId != newPartyId) {
//			sendCompanyEntrustFileNotification(compid);
//		}

		//如果企业对应的商务经理改变了 修改对应的客户表中的商务
		CrmCustomer crmCustomer = new CrmCustomer().selectOne(Condition.create().eq("compid", compid).eq("status", 1));
		if (null != crmCustomer && null != crmCustomer.getCustPerson()) {
			//查询到当前客户对应的负责人
			CrmSystemManager crmSystemManager = new CrmSystemManager().selectById(crmCustomer.getCustPerson());
			if (null != crmSystemManager && 0 != crmSystemManager.getBusinessManagerId()) {
				//判断当前该客户的负责人对应的商务经理和 企业编辑之后的商务经理是否一样 不一样更新当前客户的负责人(已企业为准)
				if (!crmSystemManager.getBusinessManagerId().equals(reqdata.getBusinessManagerId())) {
					CrmSystemManager nowSystemManager = new CrmSystemManager().selectOne(
							Condition.create().eq("business_manager_id", reqdata.getBusinessManagerId()).eq("state", 1));
					if (null == nowSystemManager) {
						return smartResult(StatusMsg.StatusMsg_335);
					}
					//添加商务经理变更记录
					String describe;
					//记录前负责人ID
					int frontDutyId = 0;
					if (null == crmCustomer.getCustPerson() || 0 == crmCustomer.getCustPerson()) {
						describe = "负责人由   变更为" + nowSystemManager.getManagername();
					} else {
						CrmSystemManager leader = new CrmSystemManager().selectById(crmCustomer.getCustPerson());
						if (null == leader) {
							describe = "负责人由   变更为" + nowSystemManager.getManagername();
						} else {
							frontDutyId = leader.getManagerid();
							describe = "负责人由" + leader.getManagername() + "变更为" + nowSystemManager.getManagername();
						}
						ChangeRecord changeRecord = new ChangeRecord();
						changeRecord.setCustId(crmCustomer.getCustId());
						changeRecord.setDescribe(describe);
						changeRecord.setOperatorId(formBean.getUserid());
						changeRecord.setFrontDutyId(frontDutyId);
						if (!changeRecord.insert()) {
							LogUtil.error("客户列表修改负责人-新增负责人变更记录失败！");
						}
					}
					crmCustomer.setCustPerson(nowSystemManager.getManagerid()).updateById();
					//商务经理发生变更，通知变更后的商务经理
					String info = "企业" + company.getCompname() + "的商务经理变更为您，请及时跟进。";
					new Thread(() -> {
						commonService.sendEnterpriseWeChatNotice(nowSystemManager.getBusinessManagerId(),
								nowSystemManager.getManagername(),
								1, info);
					}).start();

				}
			}
			//修改企业名称要同步到CRM客户表，并发通知给商务
			if (!crmCustomer.getCustName().equals(reqdata.getCompname())) {
				// 发送通知给 商务经理
				String info = "当前企业" + companyName + "变更名称为:" + reqdata.getCompname() + "，请您及时查看。";
				// 进行 同步 客户名称
				crmCustomer.setCustName(reqdata.getCompname());
				crmCustomer.updateById();
				commonService.sendEnterpriseWeChatNotice(reqdata.getBusinessManagerId(), "", 1, info);
			}

		}
		//企业开通合销云时默认生成表单
		if (reqdata.getMarketingCooperative() == 1){
			Company companys = new Company().selectById(compid);
			if(companys != null) {
				MarketingCooperativeCompanyForm whether = new MarketingCooperativeCompanyForm()
						.selectOne(Condition.create().eq("compid", company.getCompid()));
				if (whether == null) {
					MarketingCooperativeCompanyForm Form = new MarketingCooperativeCompanyForm();
					Form.setCompid(company.getCompid()).setName("营销");
					if (Form.insert()) {
						MarketingCooperativeCompanyFormItem item = new MarketingCooperativeCompanyFormItem();
						item.setCompid(Form.getCompid())
								.setFormId(Form.getId())
								.setType(1)
								.setColumnName("col1")
								.setName("联系人");
						if (item.insert()) {
							MarketingCooperativeCompanyFormItem item1 = new MarketingCooperativeCompanyFormItem();
							item1.setCompid(Form.getCompid())
									.setFormId(Form.getId())
									.setType(1)
									.setColumnName("col2")
									.setName("联系方式");
							if (item1.insert()) {
								MarketingCooperativeCompanyFormItem item2 = new MarketingCooperativeCompanyFormItem();
								item2.setCompid(Form.getCompid())
										.setFormId(Form.getId())
										.setType(2)
										.setColumnName("col3")
										.setName("业务需求").insert();
							}
						}
					}
				}
			}
		}
		return smartResult();
	}

	/**
	 * 检索企业列表
	 */
	public SmartResult queryCompanyList(BaseSimpleFormBean<String> formBean) {
		String compname = formBean.getReqdata();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CompanyBriefDto> list = companyMapper.getCompanyBriefByName(compname);
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult createCompany(BaseSimpleFormBean<CreateCompanyFormBean> formBean) {

		CreateCompanyFormBean reqdata = formBean.getReqdata();

		int count = new Company().selectCount(Condition.create()
				.eq("compname", reqdata.getCompname())
				.or()
				.eq("creditcode", reqdata.getCreditcode())
				.or()
				.eq("regphone", reqdata.getRegphone()));
		if (count > 0) return smartResult(StatusMsg.StatusMsg_108);

		Company company = new Company();
		BeanUtils.copyProperties(reqdata, company);

		String password = reqdata.getPassword();
		if (password == null) password = "";
		String payPassword = reqdata.getPayPassword();
		if (payPassword == null) payPassword = "";

		String salt = RandomUtil.getRandomStr(8);
		String encodePassword = MD5Util.md5(password + salt);
		String paySalt = RandomUtil.getRandomStr(8);
		String encodePayPassword = MD5Util.md5(payPassword + paySalt);

		company.setPassword(encodePassword).setSalt(salt).setState(Constants.comp_state_2).setRegfrom(2).insert();

		new CompanyAccount().setCompid(company.getCompid())
				.setEconomyCategoryId(reqdata.getEconomyCategoryId())
				.setPayPassword(encodePayPassword)
				.setSalt(paySalt)
				.setWhetherSubject(reqdata.getWhetherSubject())
				.setVerifyPhone(reqdata.getVerifyPhone())
				.setChangeNotes(reqdata.getChangeNotes())
				.setAuthSubmitTime(new Date())
//				.setPayType(reqdata.getPayType())
				.setShowZhaoshangLedger(reqdata.getShowZhaoshangLedger())
				.setMarketingCooperative(reqdata.getMarketingCooperative())
				.insert();
		//企业开通合销云时默认生成表单
		if (reqdata.getMarketingCooperative() == 1){
			Company companys = new Company().selectById(company.getCompid());
			if(companys != null) {
				MarketingCooperativeCompanyForm whether = new MarketingCooperativeCompanyForm()
						.selectOne(Condition.create().eq("compid", company.getCompid()));
				if (whether == null) {
					MarketingCooperativeCompanyForm Form = new MarketingCooperativeCompanyForm();
					Form.setCompid(company.getCompid()).setName("营销");
					if (Form.insert()) {
						MarketingCooperativeCompanyFormItem item = new MarketingCooperativeCompanyFormItem();
						item.setCompid(Form.getCompid())
								.setFormId(Form.getId())
								.setType(1)
								.setColumnName("col1")
								.setName("联系人");
						if (item.insert()) {
							MarketingCooperativeCompanyFormItem item1 = new MarketingCooperativeCompanyFormItem();
							item1.setCompid(Form.getCompid())
									.setFormId(Form.getId())
									.setType(1)
									.setColumnName("col2")
									.setName("联系方式");
							if (item1.insert()) {
								MarketingCooperativeCompanyFormItem item2 = new MarketingCooperativeCompanyFormItem();
								item2.setCompid(Form.getCompid())
										.setFormId(Form.getId())
										.setType(2)
										.setColumnName("col3")
										.setName("业务需求").insert();
							}
						}
					}
				}
			}
		}

		return smartResult(company.getCompid());
	}

	public SmartResult delCompany(BaseSimpleFormBean<Integer> formBean) {

		Integer compid = formBean.getReqdata();
		Company company = new Company().selectById(compid);
		if (company == null) return smartResult(StatusMsg.StatusMsg_302);

		int projectCount = new CompanyProject().selectCount(Condition.create().eq("compid", compid));
		if (projectCount > 0) {
			return smartResult(StatusMsg.StatusMsg_306);
		}

		if (company.getState() >= 4) {
			return smartResult(StatusMsg.StatusMsg_306);
		}

		company.deleteById();

		CompanyAccount companyAccount = companyAccountMapper.selectById(compid);
		if(companyAccount != null){
			companyAccount.deleteById();
		}
		return smartResult();
	}

	public SmartResult changeCompanyState(BaseSimpleFormBean<CompanyStateFormBean> formBean) {

		CompanyStateFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();
		int state = reqdata.getState();
		if (state <= 0 || state > 5) {
			return errorParamSmartResult();
		}
		Company company = companyMapper.selectById(reqdata.getCompid());
		if (null == company) {
			return smartResult(StatusMsg.StatusMsg_302);
		}
		company.setState(state).updateById();

		CompanyAccount companyAccount = companyAccountMapper.getByCompid(company.getCompid());
		//通知商务经理
		new Thread(() -> commonService.enterpriseAutomaticFreezing(companyAccount.getBusinessManagerId(), company.getCompname()+"该企业已被冻结。")).start();

		return smartResult();
	}

	public SmartResult setCompanyFriendlyState(BaseSimpleFormBean<CompanyFriendlyStateFormBean> formBean) {

		CompanyFriendlyStateFormBean reqdata = formBean.getReqdata();
		int friendlyState = reqdata.getFriendlyState();
		new Company().setCompid(reqdata.getCompid()).setFriendlyState(friendlyState).updateById();
		return smartResult();
	}

	//开通委托接单功能
	public SmartResult setEntrustedReceiptStatus(BaseSimpleFormBean<EntrustedReceiptStatusFormBean> formBean) {

		EntrustedReceiptStatusFormBean reqdata = formBean.getReqdata();
		int entrustedReceiptStatus = reqdata.getEntrustedReceiptStatus();
		if (entrustedReceiptStatus == 0 || entrustedReceiptStatus == 1) {
			new Company().setCompid(reqdata.getCompid()).setEntrustedReceiptStatus(entrustedReceiptStatus).updateById();
		} else {
			return errorParamSmartResult();
		}
		return smartResult();
	}

	public SmartResult reverifyCompany(BaseSimpleFormBean<VerifyCompanyFormBean> formBean) {
		VerifyCompanyFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int adminid = formBean.getUserid();
		int compid = reqdata.getCompid();
		String reason = reqdata.getReason();
		String remark = reqdata.getRemark();
		Company company = new Company().selectById(compid);
		if (company == null) return errorParamSmartResult();

		if (company.getState() != Constants.comp_state_4) {
			return smartResult(StatusMsg.StatusMsg_313);
		}

		company.setState(Constants.comp_state_3).updateById();
		new CompanyAccount().setRealnameAuth(Constants.comp_auth_1).update(Condition.create().eq("compid", compid));
		new CompanyAuthRecord().setAdminid(adminid).setCompid(compid).setState(1).setReason(reason).setRemark(remark).insert();
		//结果通知企业
		wxMessageService.compAuthState(compid);
		return smartResult();
	}

	public SmartResult addCompanyKltMerchant(BaseSimpleFormBean<AddMerchantFormBean> formBean) {

		AddMerchantFormBean reqdata = formBean.getReqdata();
		if (reqdata == null || reqdata.getCompid() <= 0) return errorParamSmartResult();

		int compid = reqdata.getCompid();
		CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		if (account == null) return smartResult(StatusMsg.StatusMsg_302);

		//标准的请求参数
		MerchantFormBean m = new MerchantFormBean();
		BeanUtils.copyProperties(reqdata, m);

		String kltreq = DateUtil.getNowDateString(DateUtil.FORMAT_STYLE_11);
		m.setFullNameCn(reqdata.getCompname())
				.setNameCn(reqdata.getCompname())
				.setPan(reqdata.getAcctno())
				.setTaxRegNo(reqdata.getCreditcode())
				.setLicenseNo(reqdata.getCreditcode())
				.setMerchantRequestSeq(kltreq);

		RestTemplate restTemplate = new RestTemplate();
		BaseSimpleFormBean<MerchantFormBean> addFormBean = new BaseSimpleFormBean<>();
		addFormBean.setReqdata(m);

		SmartResult smartResult = restTemplate.postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getAddMerchantUrl(), addFormBean,
				SmartResult.class);
		if (smartResult != null && smartResult.getState() == StatusMsg.StatusMsg_100.getState()) {
			//请求成功
			AddMerchantResultDto resultDto = null;
			try {
				resultDto = JSON.parseObject(JSON.toJSONString(smartResult.getObject()), AddMerchantResultDto.class);
			} catch (Exception ignored) {
			}
			if (resultDto == null || StringUtil.isEmpty(resultDto.getKltMerchantIdSeq())) {
				return smartResult(StatusMsg.StatusMsg_452);
			}

			//更新操作
			account.setMerchantRequestSeq(kltreq).setKltMerchantIdSeq(resultDto.getKltMerchantIdSeq()).updateById();
		}
		return smartResult;
	}

	public SmartResult queryKltMerchant(BaseSimpleFormBean<Integer> formBean) {

		Integer compid = formBean.getReqdata();
		CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		if (account == null) return errorParamSmartResult();

		String kltMerchantIdSeq = account.getKltMerchantIdSeq();
		BaseSimpleFormBean<String> requestBean = new BaseSimpleFormBean<>();
		requestBean.setReqdata(kltMerchantIdSeq);

		RestTemplate restTemplate = new RestTemplate();
		SmartResult smartResult = restTemplate.postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getQueryMerchantUrl(), requestBean,
				SmartResult.class);

		if (smartResult != null && smartResult.getState() == StatusMsg.StatusMsg_100.getState()) {
			//请求成功
			QueryMerchantResultDto resultDto = null;
			try {
				resultDto = JSON.parseObject(JSON.toJSONString(smartResult.getObject()), QueryMerchantResultDto.class);
			} catch (Exception ignored) {

			}
			if (resultDto == null) {
				return smartResult(StatusMsg.StatusMsg_199);
			}
			account.setKltMerchantState(StringUtil.toInt(resultDto.getCheckStatus()))
					.setMerchantid(resultDto.getMerchantId())
					.setMd5key("")
					.updateById();
		}

		return smartResult;
	}

	public SmartResult editInviteCode(BaseSimpleFormBean<EditInviteCodeFormBean> formBean) {
		EditInviteCodeFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int compid = reqdata.getCompid();
		String inviteCode = reqdata.getInviteCode();

		new Company().setCompid(compid).setInviteCode(inviteCode).updateById();
		return smartResult();
	}

	public SmartResult setCompanyCrowdsource(BaseSimpleFormBean<SetCompanyCrowdsourceFormBean> formBean) {

		SetCompanyCrowdsourceFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int compid = reqdata.getCompid();
//		int crowdsourceCity = reqdata.getCrowdsourceCity();
//		CityConfig cityConfig = new CityConfig().selectById(crowdsourceCity);
//		Asserts.notNull(cityConfig, StatusMsg.StatusMsg_618);
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		Asserts.notNull(companyAccount, StatusMsg.StatusMsg_302);
		// 切换众包城市的时候不能有未完成的单子
		//2020/12/10注释掉  系统不限制城市和支付方式，去掉切换城市时余额为0的限制
		//		int unfinishProject = crowdsourceProjectMapper.countUnfinishProject(compid);
		//		Asserts.equalZero(unfinishProject, StatusMsg.StatusMsg_621);

		// 智众包城市天津(九歌) --> 企业支付方式必须是得仕九歌商户号, 九歌线下支付
		// 智众包城市共青城(武圣) --> 企业支付方式必须是得仕武圣商户号 , 传化武圣商户号, 九歌线下支付
		//2020/12/10注释掉  系统不限制城市和支付方式，去掉切换城市时余额为0的限制
		//		Integer payType = companyAccount.getPayType();
		//		Integer merchantType = cityConfig.getZddMerchantType();
		//		Asserts.isTrue((merchantType == ZddMerchantType.DAYS_JIUGE && NumberUtil.intIn(payType, CompanyPayType.DAYS_JIUGE,
		//		CompanyPayType.JIUGE_OFFLINE)) ||
		//				(merchantType == ZddMerchantType.DAYS_WUSHENG &&
		//						 NumberUtil.intIn(payType, CompanyPayType.DAYS_WUSHENG, CompanyPayType.TRANSFER_WUSHENG, CompanyPayType
		//						 .JIUGE_OFFLINE)),
		//				StatusMsg.StatusMsg_620);

		Company company = new Company().selectById(compid);
		BeanUtils.copyProperties(reqdata, company);
		company.setIntelCrowdsource(reqdata.getCrowdsource());

//		// 切换了支付方式，如果是招商银行，检查是否创建了记账子单元
//		if (companyAccount.getPayType() != reqdata.getPayType() && CompanyPayType.isZhaoShangPayType(reqdata.getPayType())) {
//			// 新建记账子单元
//			zhaoShangTradeBulterService.createSubLedgerIfNotExist(company, reqdata.getPayType());
//		}

		if (company.updateById()) {
			new CompanyAccount().setEconomyCategoryId(reqdata.getEconomyCategoryId())
					.setVerifyPhone(reqdata.getVerifyPhone())
//					.setPayType(reqdata.getPayType())
					.setTaxSourceId(reqdata.getTaxSourceId())
					.update(Condition.create().eq("compid", compid));
			return smartResult();
		} else return optFailSmartResult();
	}

	public SmartResult getIntelCrowdsourceList(BaseSimpleFormBean<String> formBean) {
		String compname = formBean.getReqdata();
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyMapper.getIntelCrowdsourceCompany(compname);
		return smartResultPage(page);
	}

	public SmartResult companyRescission(BaseSimpleFormBean<Integer> formBean) {
		Integer compid = formBean.getReqdata();
		Company company = new Company().selectById(compid);
		if (null == company) {
			return smartResult(StatusMsg.StatusMsg_302);
		}
		company.setState(7);
		if (!company.updateById()) {
			return smartResult(StatusMsg.StatusMsg_199);
		}
		CompanyAccount companyAccount = companyAccountMapper.getByCompid(company.getCompid());
		//通知商务经理
		new Thread(() -> commonService.enterpriseAutomaticFreezing(companyAccount.getBusinessManagerId(), company.getCompname()+"该企业已被解约。")).start();
		return smartResult();
	}

	public SmartResult editCoreModule(BaseSimpleFormBean<CoreModuleFormBean> formBean) {
		@Valid CoreModuleFormBean reqdata = formBean.getReqdata();
		int compid = reqdata.getCompid();
		String coreModule = reqdata.getCoreModule();

		CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		if (account == null) return smartResult(StatusMsg.StatusMsg_302);

		account.setCoreModule(coreModule).updateAllColumnById();
		return smartResult();
	}


	public SmartResult editStrategyInvoice(BaseSimpleFormBean<CompanyStrategyInvoiceFormBean> formBean) {
		@Valid CompanyStrategyInvoiceFormBean reqdata = formBean.getReqdata();
		int compid = reqdata.getCompid();
		int strategyInvoice = reqdata.getStrategyInvoice();

		CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		if (account == null) return smartResult(StatusMsg.StatusMsg_302);

		account.setStrategyInvoice(strategyInvoice).updateAllColumnById();
		return smartResult();
	}

	/**
	 * 催促企业上传 众包证据链
	 * 发送给企业：
	 * 您有x个共享经济众包项目尚未系统上传《完工验收&结算确认单》（或创客交付成果证据链）：yyyy-mm-dd hh:mm:ss-项目名称，yyyy-mm-dd hh:mm:ss-项目名称，yyyy-mm-dd
	 * hh:mm:ss-项目名称，请及时上传。如有问题请咨询客服JUDY，或拨打全国客服电话17710090008。
	 * 发送给商务经理：
	 * 以下企业已完成共享经济众包项目交易但系统尚未上传《完工验收&结算确认单》（或创客交付成果证据链）：企业A有6个，企业B有2个，请及时跟进完成。
	 * 发送给胡总：
	 * 以下企业已完成共享经济众包项目交易但系统尚未上传《完工验收&结算确认单》（或创客交付成果证据链）：企业A有6笔，企业B有2笔。
	 * （3次以后只发给商务和胡总）
	 * 从2021年开始的项目
	 */
	public void urgeUploadProjectFile() {
		LogUtil.info("-----------------------进入催促企业上传众包证据链任务--------------------------");
		//查询需要催促上传众包任务证据链的项目信息 对应企业信息  对应商务经理信息
		// (发送给企业的)
		List<UrgeUploadProjectFileDto> urgeCompanyList = crowdsourceProjectMapper.urgeUploadProjectFileToCompany();
		//(发送给企业对应的商务经理的)
		List<UrgeUploadProjectFileDto> urgeBusinessManagerList = crowdsourceProjectMapper.urgeUploadProjectFileToBusinessManager();
		//(发送给胡总的)
		List<UrgeUploadProjectFileDto> urgeBossList = crowdsourceProjectMapper.urgeUploadProjectFileToBoss();

		if (null != urgeCompanyList && 0 < urgeCompanyList.size()) {
			//给企业发送催促上传众包证据链信息
			urgeUploadProjectFileToCompany(urgeCompanyList);
		}
		if (null != urgeBusinessManagerList && 0 < urgeBusinessManagerList.size()) {
			//给商务经理发送信息
			urgeUploadProjectFileToBusinessManager(urgeBusinessManagerList);
		}
		if (null != urgeBossList && 0 < urgeBossList.size()) {
			//给胡总发信息
			urgeUploadProjectFileToBoss(urgeBossList);
		}

		if (null != urgeBusinessManagerList && 0 < urgeBusinessManagerList.size()) {
			//根据查询的sql可以确定  只要满足发给 企业 和 胡总的 数据， 一定在 商务经理 的数据中，所以遍历项目  催送次数加一
			for (UrgeUploadProjectFileDto urgeUploadProjectFileDto : urgeBusinessManagerList) {
				CrowdsourceProject crowdsourceProject = new CrowdsourceProject().selectById(urgeUploadProjectFileDto.getProjectid());
				crowdsourceProject.setUrgeUploadProjectFileCount(crowdsourceProject.getUrgeUploadProjectFileCount() + 1).updateById();
			}
		}
	}

	/**
	 * 给企业发送催促上传众包证据链信息
	 *
	 * @param list
	 * @return
	 */
	private void urgeUploadProjectFileToCompany(List<UrgeUploadProjectFileDto> list) {
		LogUtil.info("-------------------开始给企业发送消息催促上传众包证据链----------------");
		//所得的数据根据企业id相同的分组 map<企业id,List<数据>>
		//groupingBy(根据流中元素的某个值对流中的元素进行分组,并将属性值做为结果map的键)
		Map<Integer, List<UrgeUploadProjectFileDto>> mapCompany = list.stream().collect(Collectors.groupingBy(dto -> dto.getCompid()));
		for (Integer integer : mapCompany.keySet()) {
			List<UrgeUploadProjectFileDto> projectByCompany = mapCompany.get(integer);
			int size = projectByCompany.size();
			String text = "您有" + size + "个共享经济众包项目尚未系统上传《完工验收&结算确认单》（或创客交付成果证据链）：";
			String projectName = "";
			for (UrgeUploadProjectFileDto companyPrioject : projectByCompany) {
				if (StringUtils.isEmpty(projectName)) {
					projectName = companyPrioject.getCreatetime() + "-" + companyPrioject.getProjectName();
				} else {
					projectName += "，" + companyPrioject.getCreatetime() + "-" + companyPrioject.getProjectName();
				}
			}
			CompanyAccount companyAccount = new CompanyAccount().selectOne(
					Condition.create().eq("compid", projectByCompany.get(0).getCompid()));
			//给企业发送消息
			wxMessageService.urgeCompanyUploadProjectFile(projectByCompany.get(0).getCompanyOpenid(), text + projectName,
					companyAccount.getRealname(), companyAccount.getCompid());
		}
	}

	/**
	 * 给商务经理发送企业微信消息
	 *
	 * @param list List<UrgeUploadProjectFileDto>
	 * @return
	 */
	private void urgeUploadProjectFileToBusinessManager(List<UrgeUploadProjectFileDto> list) {
		LogUtil.info("---------------------------开始给商务经理发送信息催促企业上传证据链---------------------------");
		//所得的数据根据商务经理id相同的分组 map<商务经理id,List<数据>>
		//groupingBy(根据流中元素的某个值对流中的元素进行分组,并将属性值做为结果map的键)
		Map<Integer, List<UrgeUploadProjectFileDto>> mapBusinessManager = list.stream()
				.collect(Collectors.groupingBy(dto -> dto.getBusinessManagerId()));
		for (Integer integer : mapBusinessManager.keySet()) {
			String text = "以下企业已完成共享经济众包项目交易但系统尚未上传《完工验收&结算确认单》（或创客交付成果证据链）：";
			String end = "，请及时跟进完成。";
			List<UrgeUploadProjectFileDto> projectByBusinessManager = mapBusinessManager.get(integer);
			//再根据企业分组
			Map<Integer, List<UrgeUploadProjectFileDto>> mapCompany = projectByBusinessManager.stream()
					.collect(Collectors.groupingBy(companyList -> companyList.getCompid()));
			//构建信息（企业A有6笔，企业B有2笔，）
			String companyText = constructUrgeInformation(mapCompany);
			//给商务经理发送企业微信消息
			commonService.sendEnterpriseWeChatNotice(projectByBusinessManager.get(0).getBusinessManagerId(),
					projectByBusinessManager.get(0).getBusinessManager(), 1, text + companyText + end);
		}
	}

	/**
	 * 给胡总发送企业微信消息
	 *
	 * @param list List<UrgeUploadProjectFileDto>
	 * @return
	 */
	private void urgeUploadProjectFileToBoss(List<UrgeUploadProjectFileDto> list) {
		LogUtil.info("--------------------------开始给胡总发信息催促企业上传证据链-------------------------");
		//所得的数据 根据企业id相同的分组 map<企业id,List<数据>>
		//groupingBy(根据流中元素的某个值对流中的元素进行分组,并将属性值做为结果map的键)
		Map<Integer, List<UrgeUploadProjectFileDto>> mapCompany = list.stream().collect(Collectors.groupingBy(dto -> dto.getCompid()));
		String text = "以下企业已完成共享经济众包项目交易但系统尚未上传《完工验收&结算确认单》（或创客交付成果证据链）：";
		//构建信息（企业A有6笔，企业B有2笔，）
		String bossText = constructUrgeInformation(mapCompany);
		//给商务经理发送企业微信消息
		commonService.sendEnterpriseWeChatNotice(0, "胡刚", 2, text + bossText);
	}

	/**
	 * 构建信息  : 企业A有6笔，企业B有2笔，
	 *
	 * @param mapCompany Map<Integer,List<UrgeUploadProjectFileDto>>
	 * @return String
	 */
	private String constructUrgeInformation(Map<Integer, List<UrgeUploadProjectFileDto>> mapCompany) {
		String text = "";
		for (Integer integer : mapCompany.keySet()) {
			List<UrgeUploadProjectFileDto> projectByCompany = mapCompany.get(integer);
			//该企业有几条数据（项目）
			int size = projectByCompany.size();
			if (StringUtils.isEmpty(text)) {
				text = projectByCompany.get(0).getCompname() + "有" + size + "笔";
			} else {
				text += "，" + projectByCompany.get(0).getCompname() + "有" + size + "笔";
			}
		}
		return text;
	}

	/**
	 * 注册后并审核通过 但从没交易过的企业，发送提醒消息给商务经理；
	 */
	public void noticeBusinessForNotTradedCompany() {

		//获取 审核通过但从未交易过  项目 或 智众包项目 的企业（草稿项目 删除的 取消的 项目 不算在内）
		List<CompanyManagerDto> list = companyMapper.getNotTradeCompany();
		if (!CollectionUtils.isEmpty(list)) {
			list.stream().collect(Collectors.groupingBy(CompanyManagerDto::getBusinessManagerId)).forEach((id, businessList) -> {
				try {
					if (CollectionUtils.isEmpty(businessList)) {return;}
					String names = businessList.stream().map(CompanyManagerDto::getCompname).collect(Collectors.joining("，"));
					String text = "以下企业注册并审核通过后还未交易过：" + names + "，请及时跟进催促！";
					commonService.sendEnterpriseWeChatNotice(id, "", 1, text);
				} catch (Exception e) {
					log.info("商务消息id={}：以下企业注册后还未交易过 报错", id, e);
				}
			});
			list.stream().collect(Collectors.groupingBy(CompanyManagerDto::getMerchandiserId)).forEach((id, businessList) -> {
				try {
					if (CollectionUtils.isEmpty(businessList)) {return;}
					String names = businessList.stream().map(CompanyManagerDto::getCompname).collect(Collectors.joining("，"));
					String text = "以下企业上一个月未曾交易：" + names + "，请及时跟进催促！";
					commonService.sendEnterpriseWeChatNotice(id, "", 1, text);
				} catch (Exception e) {
					log.info("跟单员消息id={}：以下企业上一个月未曾交易 报错", id, e);
				}
			});
		}
	}

	/**
	 * 注册后并审核通过 但从没交易过的企业，发送提醒消息给商务经理；
	 */
	public void noticeBusinessForOneMonthNotTradedCompany() {
		//获取上一个月
		Date lastMonth = DateUtil.getLastMonthBeginDate();

		//获取 注册后并审核通过 但上一个月  项目 智众包项目 都没交易过的企业 发送提醒消息给商务经理；（草稿项目 删除的 取消的 项目 不算在内）
		List<CompanyManagerDto> list = companyMapper.noticeBusinessForOneMonthNotTradedCompany(lastMonth);
		if (!CollectionUtils.isEmpty(list)) {
			list.stream().collect(Collectors.groupingBy(CompanyManagerDto::getBusinessManagerId)).forEach((id, businessList) -> {
				try {
					if (CollectionUtils.isEmpty(businessList)) {return;}
					String names = businessList.stream().map(CompanyManagerDto::getCompname).collect(Collectors.joining("，"));
					String text = "以下企业上一个月未曾交易：" + names + "，请及时跟进催促！";
					commonService.sendEnterpriseWeChatNotice(id, "", 1, text);
				} catch (Exception e) {
					log.info("商务消息id={}：以下企业上一个月未曾交易 报错", id, e);
				}
			});
		}
	}

	/**
	 * 众包企业设置众包项目中合同的起始日期
	 *
	 * @param formBean formBean
	 * @return smartResult
	 */
	public SmartResult setCrowdsourceContractDate(BaseSimpleFormBean<SetContractDateFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getCompid()) {
			return errorParamSmartResult();
		}
		SetContractDateFormBean reqdata = formBean.getReqdata();
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", reqdata.getCompid()));
		if (companyAccount == null) {
			return smartResult(StatusMsg.StatusMsg_302);
		}
		companyAccount.setContractStartDate(reqdata.getContractStartDate()).setContractEndDate(reqdata.getContractEndDate()).updateById();
		return smartResult();
	}

	public SmartResult supplementKingdeeCustomerCode(MultipartFile file) {
		if (!file.isEmpty()) {
			List<ImportKingdeeCustomerCodeFormBean> list = Lists.newArrayList();
			try {
				EasyExcel.read(file.getInputStream(), ImportKingdeeCustomerCodeFormBean.class,
						new ZddReadListener<ImportKingdeeCustomerCodeFormBean>() {
							@Override
							public void invoke(ImportKingdeeCustomerCodeFormBean data, AnalysisContext context) {
								list.add(data);
							}
						}).sheet().doRead();
			} catch (IOException e) {
				log.error("导入金蝶客户信息失败", e);
			}
			//循环根据企业名获取企业信息
			list.forEach(bean -> {
				Company company = new Company().selectOne(Condition.create().eq("compname", bean.getCompanyName()).eq("state", 4));
				if (null == company) {
					LogUtil.error("补充企业金蝶客户编码-企业不存在！企业名称：" + bean.getCompanyName());
					return;
				}
				company.setKingdeeCustomerCode(bean.getCustomerCode());
				if (!company.updateById()) {
					LogUtil.error("补充企业金蝶客户编码-修改企业失败！企业名称：" + bean.getCompanyName());
				}
			});
		}
		return errorParamSmartResult();
	}

	public SmartResult setSpecialRateFlag(int compid, int specialRateFlag) {
		new Company().setCompid(compid).setSpecialRateFlag(specialRateFlag).updateById();
		return SmartResult.success();
	}

	public SmartResult setMakerGroupon(BaseSimpleFormBean<SetMakerGrouponFormBean> formBean) {
		@Valid SetMakerGrouponFormBean reqdata = formBean.getReqdata();
		int compid = reqdata.getCompid();
		CompanyAccount account = companyAccountMapper.getByCompid(compid);
		Asserts.notNull(account, StatusMsg.StatusMsg_302);

		account.setMakerGroupon(reqdata.getMakerGroupon());
		account.setPrincipalId(reqdata.getPrincipalId());
		account.updateById();
		return SmartResult.success();
	}

	public SmartResult<CompanyTransferMakerGrouponDto> listApplyTransferMakerGroupon(
			BaseSimpleFormBean<ListTransferMakerGrouponFormBean> formBean) {
		@Valid ListTransferMakerGrouponFormBean reqdata = formBean.getReqdata();
		Page<CompanyTransferMakerGrouponDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyTransferMakerGrouponMapper.list(reqdata.getName(), reqdata.getState(), reqdata.getFrom(), reqdata.getTo());
		return SmartResult.ofPage(page);
	}

	public SmartResult confirmTransferMakerGroupon(BaseSimpleFormBean<Integer> formBean) {
		@Valid Integer id = formBean.getReqdata();
		int userid = formBean.getUserid();
		CompanyTransferMakerGroupon transInfo = new CompanyTransferMakerGroupon().selectById(id);
		Asserts.notNull(transInfo, StatusMsg.StatusMsg_354);
		Asserts.isTrue(transInfo.getState() == CompanyTransferMakerGrouponState.APPLIED, StatusMsg.StatusMsg_359);

		Integer compid = transInfo.getCompid();
		BigDecimal amount = transInfo.getAmount();
		transInfo.setState(CompanyTransferMakerGrouponState.FINISHED)
				.setFinishTime(new Date())
				.setAdminid(userid)
				.updateById();

		CompanyPayment fromPayment = new CompanyPayment().selectById(transInfo.getFromCompPayId());
		CompanyPayment toPayment = new CompanyPayment().selectById(transInfo.getToCompPayId());

		// 修改企业转入账户余额, 修改转出账户冻结金额
		BigDecimal beforeBalance = toPayment.getBalance();
		fromPayment.setFrozenBalance(fromPayment.getFrozenBalance().subtract(transInfo.getAmount())).updateById();
		toPayment.setBalance(toPayment.getBalance().add(transInfo.getAmount())).updateById();

		//生成企业流水
		CompanyAccountflow accountflow = new CompanyAccountflow().setCompid(compid)
				.setFlowname("转账到创客团账本")
				.setFlowtype(1)
				.setBizid(transInfo.getId())
				.setBizType(CompanyAccountFlowBizType.MAKER_GROUPON)
				.setAccountType(CompanyAccountFlowAccountType.MAKER_GROUPON)
				.setFlowAmount(amount)
				.setPayId(fromPayment.getPayId())
				.setBeforeBalance(beforeBalance)
				.setCurrBalance(toPayment.getBalance())
				.setBeforeFrozenBalance(toPayment.getFrozenBalance())
				.setCurrFrozenBalance(toPayment.getFrozenBalance());
		if (!accountflow.insert()) {
			throw new RollbackException("确认转账到创客团账本失败");
		}

		return SmartResult.success();
	}

	/**
	 * 上传委托文件接口
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult saveCompanyEntrustFile(BaseSimpleFormBean<SaveCompanyEntrustFileFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata().getCompid()) {
			return errorParamSmartResult();
		}
		SaveCompanyEntrustFileFormBean reqdata = formBean.getReqdata();
		Integer compid = reqdata.getCompid();
		Company company = new Company().selectById( compid);
		Asserts.notNull(company);
		CompanyParty companyParty = coreCompanyService.getCompanyDefaultPartyMul(compid,reqdata.getWorkType());
		Asserts.notNull(companyParty, StatusMsg.StatusMsg_384);

		CompanyEntrustFile companyEntrustFile = new CompanyEntrustFile().setCompid(compid)
				.setAuditState(2)
				.setPartyId(companyParty.getPartyId())
				.setWorkType(reqdata.getWorkType())
				.setEntrustFile(reqdata.getEntrustFile())
				.setEntrustStartTime(reqdata.getEntrustStartTime())
				.setEntrustEndTime(reqdata.getEntrustEndTime());
		companyEntrustFile.insert();

		// 修改通知为已完成
		companyEntrustFileNotificationMapper.updateState(compid);
		return smartResult();
	}

	public SmartResult<CompanyEntrustFileNotification> listCompanyEntrustFileNotification(
			BaseSimpleFormBean<ListCompanyEntrustFileNotificationFormBean> formBean) {
		ListCompanyEntrustFileNotificationFormBean reqdata = formBean.getReqdata();
		Date from = DateUtil.defaultInitial(reqdata.getFrom());
		Date to = DateUtil.defaultNow(reqdata.getTo());

		Page<CompanyEntrustFileNotification> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyEntrustFileNotificationMapper.listByCompnameDate(reqdata.getName(), reqdata.getState(), from, to);

		return SmartResult.ofPage(page);
	}

	public SmartResult<CompanyEntrustFile> listCompanyEntrustFile(BaseSimpleFormBean<ListCompanyEntrustFileFormBean> formBean) {
		ListCompanyEntrustFileFormBean reqdata = formBean.getReqdata();
		Date from = DateUtil.defaultInitial(reqdata.getFrom());
		Date to = DateUtil.defaultEndless(reqdata.getTo());

		Page<CompanyEntrustFile> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		String orderBy = " order by entrust_end_time desc ";
		if(reqdata.getSource() == 2){
			orderBy = " order by cef.audit_state = 1 desc,entrust_end_time desc ";
		}
		List<CompanyEntrustFile> list = companyEntrustFileMapper.listByCompnameDate(reqdata.getCompId(),reqdata.getName(), from, to, reqdata.getSource(),reqdata.getWorkType(),orderBy);

		return SmartResult.ofPage(page);
	}

	public SmartResult<CompanyEntrustFile> auditCompanyEntrustFile(BaseSimpleFormBean<AuditCompanyEntrustFileFormBean> formBean) {
		AuditCompanyEntrustFileFormBean reqdata = formBean.getReqdata();
		CompanyEntrustFile entrustFile = companyEntrustFileMapper.selectById(reqdata.getId());
		Asserts.notNull(entrustFile);

		if (reqdata.getAuditState() == 2) {
			entrustFile.setState(1);
		}

		entrustFile.setAuditState(reqdata.getAuditState())
				   .setAuditMsg(reqdata.getAuditMsg())
				   .updateById();

		// 审核通过后给企业发微信通知
		wxMessageService.notifyCompanyContractAudit(entrustFile);

		return SmartResult.success(entrustFile);
	}

	public SmartResult<CompanyEntrustFile> delCompanyEntrustFile(BaseSimpleFormBean<DelCompanyEntrustFileFormBean> formBean) {
		DelCompanyEntrustFileFormBean reqdata = formBean.getReqdata();
		//根据ID删除数据
		new CompanyEntrustFile().setId(reqdata.getId()).deleteById();
		return SmartResult.success();
	}

	/**
	 * 修改商务经理
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult updateBusinessManager(BaseSimpleFormBean<UpdateBusinessManagerFormBean> formBean) {
		UpdateBusinessManagerFormBean reqdata = formBean.getReqdata();
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", reqdata.getCompid()));
		Asserts.notNull(companyAccount);
		Asserts.isTrue(companyAccount.setBusinessManagerId(reqdata.getBusinessManagerId()).updateById());
		Company company = new Company().selectById(reqdata.getCompid());
		Asserts.notNull(company);
		//通知商务经理
		String finalInfo = company.getCompname() + "已注册，请及时填写进件表";
		new Thread(() -> commonService.sendEnterpriseWeChatNotice(reqdata.getBusinessManagerId(), null, 1, finalInfo)).start();
		return smartResult();
	}

	/**
	 * 进件表详情
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult infoIncoming(BaseSimpleFormBean<Integer> formBean) {
		Incoming incoming = new Incoming().selectOne(Condition.create().eq("compid", formBean.getReqdata()));
		if (incoming == null) {
			return smartResult();
		}
		InfoIncomingDto infoIncomingDto = new InfoIncomingDto();
		BeanUtils.copyProperties(incoming, infoIncomingDto);
		String productEntrustPrice = incoming.getProductEntrustPrice();
		if (!StringUtils.isNotBlank(productEntrustPrice)) {
			List<ProductEntrustPriceFormBean> partnerListFormBeans = JSONObject.parseArray(productEntrustPrice,
					ProductEntrustPriceFormBean.class);
			infoIncomingDto.setProductEntrustPrice(partnerListFormBeans);
		}
		return smartResult(infoIncomingDto);
	}

	/**
	 * 进件表修改
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult updateIncoming(BaseSimpleFormBean<UpdateIncomingFormBean> formBean) {
		UpdateIncomingFormBean reqdata = formBean.getReqdata();
		Incoming incoming = new Incoming();
		BeanUtils.copyProperties(reqdata, incoming);
		incoming.setMeanwhileControl(1);
		Asserts.isTrue(incoming.updateById());
		return smartResult();
	}

	/**
	 * 到期前一个星期发企业微信通知商务，续签委托函
	 */
	public void noticeBusiness() {
		// 获取7天后就到期的企业委托函
		String endDate = DateUtil.getString(DateUtil.addDay(DateUtil.nowDate(), 7),DateUtil.FORMAT_STYLE_2);
		companyEntrustFileMapper.listByEndDate(endDate).forEach(ef -> {
			sendCompanyEntrustFileNotification(ef.getCompid(),1);
		});
	}
	/**
	 * 到期合同
	 */
	public void expiredContracts() {
		// 获取到期的企业委托函
		String endDate = DateUtil.getString(DateUtil.nowDate(),DateUtil.FORMAT_STYLE_2);
		companyEntrustFileMapper.listByEndDate(endDate).forEach(ef -> {
			sendCompanyEntrustFileNotification(ef.getCompid(),2);
		});
	}
	/**
	 * 未上传合同
	 */
	public void theContractWasNotUploaded() {
		companyEntrustFileMapper.theContractWasNotUploaded().forEach(ef -> {
			sendCompanyEntrustFileNotification(ef.getCompid(),3);
		});
	}
	/**
	 * 到期发企业微信通知商务，续签委托函
	 */
	public void beExpired() {
		beExpireds(companyEntrustFileMapper.beExpired());
	}

	private void beExpireds(List<CompanyEntrustFile> comp) {
		// 所有企业名称
		List<String> compnames = Lists.newArrayList();
		// 商务经理对应的企业名称
		Map<Integer, List<String>> bmCompnames = Maps.newHashMap();
		for (CompanyEntrustFile entrustFile : comp) {
			CompanyAccount account = companyAccountMapper.getByCompid(entrustFile.getCompid());
			if (account == null) continue;
			if (account.getWhetherSubject() == 1) continue;
			// 判断是否为无效的委托协议，无效则需要通知
			if (StringUtil.isEmpty(entrustFile.getEntrustFile()) || DateUtil.isExpired(entrustFile.getEntrustEndTime())) {
				String compname = entrustFile.getCompname();
				compnames.add(compname);
				// 商务经理
				Integer businessManagerId = account.getBusinessManagerId();
				if (NumberUtil.safeInt(businessManagerId) > 0) {
					List<String> bmNames = bmCompnames.computeIfAbsent(businessManagerId, bmid -> Lists.newArrayList());
					bmNames.add(compname);
				}
			}
		}
		// 发送消息
		String format = "以下%s家企业未上传众包合同，请及时跟进：%s。";
		// 商务经理
		if (!CollectionUtils.isEmpty(bmCompnames)) {
			bmCompnames.forEach((id, list) -> {
				// 发送给企业的商务经理
				int count = list.size();
				String names = StringUtils.join(list, "、");
				commonService.sendEnterpriseWeChatNotice(id, null, 1, String.format(format, count, names));
			});
		}
	}

	/**
	 * 获取所有企业列表，不区分状态
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult selectCompanyList(BaseSimpleFormBean<CompanyQueryFormBean> formBean) {
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyMapper.selectList(Condition.create().like("compname", formBean.getReqdata().getCompanyName()));
		return smartResultPage(page);
	}

	public SmartResult batchUpdateMerchandiser(BaseSimpleFormBean<UpdateMerchandiserFormBean> formBean) {
		List<Integer> compIdList = formBean.getReqdata().getCompIdList();
		Integer businessManagerId = formBean.getReqdata().getBusinessManagerId();

		//批量修改的商务经理ID
		new CompanyAccount().setMerchandiserId(businessManagerId).update(Condition.create().in("compid", compIdList));

		return SmartResult.success();
	}

	private void sendCompanyEntrustFileNotification(int compid,int type) {
		CompanyDetailDto companyInfo = companyMapper.getCompanyInfo(compid);
		if (companyInfo == null) return;
		String info;
		if (type == 1) {
			//即将到期
			info = companyInfo.getCompname() + " 企业合同即将到期，请及时跟进";
		}else if (type == 2){
			//已经到期
			info = companyInfo.getCompname() + " 企业智众包/智零工合同己到期，请及时跟进";
		}else {
			info = companyInfo.getCompname() + " 企业未上传智众包合同，进及时跟进";
		}
		new CompanyEntrustFileNotification().setCompid(compid).setState(1).insert();
		//通知商务经理
		new Thread(() -> {
			// 发送给企业的商务经理
			commonService.sendEnterpriseWeChatNotice(companyInfo.getBusinessManagerId(), null, 1, info);
			commonService.sendEnterpriseWeChatNotice(companyInfo.getMerchandiserId(), null, 1, info);
			wxMessageService.informTheTreasurer(info);
		}).start();
	}

	//添加企业评估
	public SmartResult addEnterpriseScore(BaseSimpleFormBean<EnterpriseScoreFormBean> formBean) {
		EnterpriseScoreFormBean reqdata = formBean.getReqdata();
		//判断compid是否等于空
		if (reqdata.getCompid() == null || reqdata.getCompid() <= 0) return errorParamSmartResult();
		//总分
		int and = (reqdata.getLitigationSituation() + reqdata.getNegativePublicOpinion() + reqdata.getVipListedCompanies() +
				           reqdata.getExpenseCalculationRules() + reqdata.getIssuingAndBusinessScope() + reqdata.getContractPerfection() +
				           reqdata.getCompliantTaxPolicy() + reqdata.getComplianceWithTaxRequirements() +
				           reqdata.getPerfectionOfIssuingAmount() + reqdata.getEvidenceChainIntegrity() + reqdata.getIndustryRisk() +
				           reqdata.getFinancialRisk() + reqdata.getTaxRisk() + reqdata.getHumanRisk() + reqdata.getLegalRisk() +
				           reqdata.getEntrustedPaymentAgreement() + reqdata.getDoesTheConsultantVisit());

		EnterpriseScore enterpriseScore = new EnterpriseScore().selectOne(Condition.create().eq("compid", reqdata.getCompid()));
		//如果compid是空就添加数据
		if (enterpriseScore == null) {
			EnterpriseScore enterpriseScore1 = new EnterpriseScore();
			BeanUtils.copyProperties(reqdata, enterpriseScore1);
			enterpriseScore1.setTotalScore(and);
			enterpriseScore1.insert();
			return smartResult();
		}
		//相反就修改
		BeanUtils.copyProperties(reqdata, enterpriseScore);
		enterpriseScore.setTotalScore(and);
		enterpriseScore.updateById();
		return smartResult();
	}

	//查看评估报告
	public SmartResult<AssessmentReportDto> assessmentReport(BaseSimpleFormBean<Integer> formBean) {
		Integer compid = formBean.getReqdata();
		if (compid == null || compid <= 0) return errorParamSmartResult();
		AssessmentReportDto assessmentReportDto = enterpriseScoreMapper.AssessmentReport(compid);
		if (assessmentReportDto == null) return emptyDataSmartResult();
		return smartResult(assessmentReportDto);
	}

	//查询评估表
	public SmartResult EnterpriseScoreList(BaseSimpleFormBean<EnterpriseScoreListFormBean> formBean) {
		EnterpriseScoreListFormBean scoreList = formBean.getReqdata();
		String compname = scoreList.getCompname();
		Integer whetherToScore = scoreList.getWhetherToScore();
		if (whetherToScore == null) {
			whetherToScore = 0;
		}
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		enterpriseScoreMapper.EnterpriseScoreList(compname, whetherToScore);
		return smartResultPage(page);
	}

	/**
	 * 充值企业余额到创客团余额 confirmTransferMakerGroupon
	 *
	 * @param formBean
	 */
	@Transactional
	public SmartResult transferToGrouponBalance(BaseSimpleFormBean<CompanyGrouponBalanceFormBean> formBean) {
		CompanyGrouponBalanceFormBean reqdata = formBean.getReqdata();
		int compid = reqdata.getCompid();
		BigDecimal amount = reqdata.getTransferAmount();
		// 转账金额不能等于0
		Asserts.isTrue(amount.compareTo(BigDecimal.ZERO) != 0);
		// 转入账户查询
		CompanyPayment toPayment = new CompanyPayment().selectById(reqdata.getToCompPayId());
		Asserts.notNull(toPayment, StatusMsg.StatusMsg_330);
		//转账金额为负数,标识红冲
		if (amount.compareTo(BigDecimal.ZERO) < 0) {
			return this.transferNegative(compid, amount, toPayment, formBean.getUserid());
		}

		// 转出账户查询
		CompanyPayment fromPayment = new CompanyPayment().selectById(reqdata.getFromCompPayId());
		Asserts.notNull(fromPayment, StatusMsg.StatusMsg_330);

		// 非红冲，转账金额必须大于0
		Asserts.isTrue(amount.compareTo(BigDecimal.ZERO) > 0);
		// 企业转出账户余额必须大于要转账的金额
		Asserts.isTrue(fromPayment.getBalance().compareTo(amount) >= 0, StatusMsg.StatusMsg_310);

		// 余额转到创客团余额记录
		CompanyTransferMakerGroupon companyTransferMakerGroupon = new CompanyTransferMakerGroupon().setCompid(compid)
				.setAmount(reqdata.getTransferAmount())
				.setApplyTime(new Date())
				.setAdminid(formBean.getUserid())
				.setFinishTime(new Date())
				.setState(CompanyTransferMakerGrouponState.FINISHED)
				.setFromCompPayId(reqdata.getFromCompPayId())
				.setToCompPayId(reqdata.getToCompPayId());
		boolean insert = companyTransferMakerGroupon.insert();
		Asserts.isTrue(insert, StatusMsg.StatusMsg_199);

		// 计算/修改企业转出账户余额 余额-amount
		BigDecimal beforeFromBalance = fromPayment.getBalance();
		BigDecimal currFromBalance = fromPayment.getBalance().subtract(amount);

		fromPayment.setBalance(currFromBalance).updateById();

		//生成企业账户转出流水
		CompanyAccountflow accountflowOut = new CompanyAccountflow().setCompid(compid)
				.setFlowname("余额转出")
				.setFlowtype(2)
				.setBizid(companyTransferMakerGroupon.getId())
				.setBizType(CompanyAccountFlowBizType.MAKER_GROUPON)
				.setAccountType(CompanyAccountFlowAccountType.ZDD_UNIFY)
				.setPayId(fromPayment.getPayId())
				.setFlowAmount(amount)
				.setBeforeBalance(beforeFromBalance)
				.setCurrBalance(currFromBalance)
				.setBeforeFrozenBalance(fromPayment.getFrozenBalance())
				.setCurrFrozenBalance(fromPayment.getFrozenBalance());

		if (!accountflowOut.insert()) {
			throw new RollbackException("操作转账到创客团支付宝账户失败");
		}
		// 计算/修改企业转入账户余额 余额+amount
		BigDecimal beforeToBalance = toPayment.getBalance();
		BigDecimal currToBalance = toPayment.getBalance().add(amount);
		toPayment.setBalance(currToBalance).updateById();

		//生成企业账户转入流水
		CompanyAccountflow accountflow = new CompanyAccountflow().setCompid(compid)
				.setFlowname("余额转入")
				.setFlowtype(1)
				.setBizid(companyTransferMakerGroupon.getId())
				.setBizType(CompanyAccountFlowBizType.MAKER_GROUPON)
				.setAccountType(CompanyAccountFlowAccountType.MAKER_GROUPON)
				.setFlowAmount(amount)
				.setPayId(toPayment.getPayId())
				.setBeforeBalance(beforeToBalance)
				.setCurrBalance(currToBalance)
				.setBeforeFrozenBalance(toPayment.getFrozenBalance())
				.setCurrFrozenBalance(toPayment.getFrozenBalance());
		if (!accountflow.insert()) {
			throw new RollbackException("操作转账到创客团账本失败");
		}
		return SmartResult.success();
	}

	/**
	 * 转账到创客团金额是负数时，标识红冲，直接减去支付宝账户余额，银行账号余额不用动
	 *
	 * @return
	 */
	public SmartResult transferNegative(int compId, BigDecimal amount, CompanyPayment toPayment, Integer adminid) {
		// 余额转到创客团余额记录
		CompanyTransferMakerGroupon companyTransferMakerGroupon = new CompanyTransferMakerGroupon().setCompid(compId)
				.setAmount(amount)
				.setApplyTime(new Date())
				.setAdminid(adminid)
				.setFinishTime(new Date())
				.setState(CompanyTransferMakerGrouponState.FINISHED)
				.setToCompPayId(toPayment.getId());
		boolean insert = companyTransferMakerGroupon.insert();
		Asserts.isTrue(insert, StatusMsg.StatusMsg_199);

		// 转入企业账户余额
		BigDecimal beforeBalance = toPayment.getBalance();
		BigDecimal currBalance = toPayment.getBalance().add(amount);
		// 更新后
		toPayment.setBalance(currBalance).updateById();

		//生成企业流水
		CompanyAccountflow accountflow = new CompanyAccountflow().setCompid(compId)
				.setPayId(toPayment.getPayId())
				.setFlowname("红冲")
				.setFlowtype(1)
				.setBizid(companyTransferMakerGroupon.getId())
				.setBizType(CompanyAccountFlowBizType.MAKER_GROUPON)
				.setAccountType(CompanyAccountFlowAccountType.MAKER_GROUPON)
				.setFlowAmount(amount)
				.setPayId(toPayment.getPayId())
				.setBeforeBalance(beforeBalance)
				.setCurrBalance(currBalance)
				.setBeforeFrozenBalance(toPayment.getFrozenBalance())
				.setCurrFrozenBalance(toPayment.getFrozenBalance());
		if (!accountflow.insert()) {
			throw new RollbackException("操作转账到创客团账本失败");
		}
		return SmartResult.success();
	}

	//添加是否代理操作账户标识，
	public SmartResult setAgentOperationAccount(BaseSimpleFormBean<AgentOperationAccountFormBean> formBean) {
		AgentOperationAccountFormBean reqdata = formBean.getReqdata();
		if (reqdata.getAgentOperationAccount() < 0 || reqdata.getAgentOperationAccount() > 1) return errorParamSmartResult();
		int agentOperationAccount = reqdata.getAgentOperationAccount();
		Company company = new Company().selectById(reqdata.getCompid());
		if (company == null) return emptyDataSmartResult();
		company.setAgentOperationAccount(agentOperationAccount).updateById();
		return smartResult();
	}

	public SmartResult queryCompanyYearlyTransAmount(BaseSimpleFormBean<QueryCompanyAmountFormBean> formBean) {
		Company company = companyMapper.selectById(formBean.getReqdata().getCompid());
		if (company == null) {
			return smartResult(StatusMsg.StatusMsg_302);
		}
		List<CompanyTransAmountDto> dtoList = new ArrayList<>();
		for (int i = DateUtil.getYear(company.getCreatetime()); i <= DateUtil.getNowYear(); i++) {
			CompanyTransAmountDto dto = companyMapper.queryCompanyYearlyTransAmount(formBean.getReqdata().getCompid(), i);
			if (dto == null) {
				dto = CompanyTransAmountDto.ofDefault(company.getCompid(), company.getCompname(), i);
			}
			dtoList.add(dto);
		}
		return SmartResult.success(dtoList);
	}

	public SmartResult<CompanyZhaoShangSubLedgerDto> listZhaoShangSubLedger(BaseSimpleFormBean<ListZhaoShangSubLedgerFormBean> formBean) {
		ListZhaoShangSubLedgerFormBean reqdata = formBean.getReqdata();
		int compid = reqdata.getCompid();
		String compname = reqdata.getCompname();
		int merchantId = reqdata.getMerchantId();
		Date from = DateUtil.defaultInitial(reqdata.getFrom());
		Date to = DateUtil.defaultNow(reqdata.getTo());

		Page<CompanyZhaoShangSubLedgerDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyZhaoshangSubLedgerMapper.listByMerchantIdAndCompname(compid, compname, merchantId, from, to);
//		.forEach(dto -> {
//			int payMerchant = ZddMerchantType.convert(PayAccount.convert(dto.getPayType()));
//			dto.setCurrentPayMerchant(payMerchant == dto.getMerchantId());
//		});
		return SmartResult.ofPage(page);
	}

	public SmartResult<CompanyZhaoshangSubLedgerRechargeDto> listZhaoShangSubLedgerRecharge(
			BaseSimpleFormBean<ListZhaoShangSubLedgerRechargeFormBean> formBean) {

		ListZhaoShangSubLedgerRechargeFormBean reqdata = formBean.getReqdata();
		String compname = reqdata.getCompname();
		int merchantId = reqdata.getMerchantId();
		String orderNo = reqdata.getOrderNo();
		Date from = DateUtil.defaultInitial(reqdata.getFrom());
		Date to = DateUtil.defaultNow(reqdata.getTo());

		Page<CompanyZhaoshangSubLedgerRechargeDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyZhaoshangSubLedgerRechargeMapper.listByMerchantIdAndName(0, compname, merchantId, orderNo, from, to);

		return SmartResult.ofPage(page);
	}

	public SmartResult editCompanyNickname(BaseSimpleFormBean<EditCompanyNicknameFormBean> formBean) {
		EditCompanyNicknameFormBean reqdata = formBean.getReqdata();
		int compid = reqdata.getCompid();
		String compnickname = StringUtil.defaultValue(reqdata.getCompnickname(), "");
		Company company = new Company().selectById(compid);
		Asserts.notNull(company, StatusMsg.StatusMsg_302);

		Asserts.notTrue(companyMapper.checkNicknameExists(compid, compnickname), StatusMsg.StatusMsg_368);
		company.setCompnickname(compnickname).updateById();
		return SmartResult.success();
	}

	public SmartResult<CompanyZhaoshangSubLedgerIncomingRecordDto> listZhaoshangSubLedgerRechargeIncomingRecords(
			BaseSimpleFormBean<Integer> formBean) {
		Integer rechargeId = formBean.getReqdata();
		List<CompanyZhaoshangSubLedgerIncomingRecordDto> list = companyZhaoshangSubLedgerIncomingRecordMapper.listByRechargeId(rechargeId);
		return SmartResult.success(list);
	}
	public SmartResult modifyDisplayList(BaseSimpleFormBean<ModifyDisplayListFormBean> formBean) {
		List<Integer> formBeans = formBean.getReqdata().getList();
		for (Integer list:formBeans) {
			CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", list));
			account.setShowZhaoshangLedger(formBean.getReqdata().getShowZhaoshangLedger())
					.update(Condition.create().eq("compid", list));
		}
		return smartResult();
	}

	public void checkCompany3MonthsNoTrade() {
		Date date = DateUtil.addDay(DateUtil.nowDate(), -180);
		List<Company> companies = companyMapper.list3MonthsNoTrade(date);
		for (Company company : companies) {
			company.setState(Constants.comp_state_5).updateById();
			CompanyAccount companyAccount = companyAccountMapper.getByCompid(company.getCompid());
			//通知商务经理
			new Thread(() -> commonService.enterpriseAutomaticFreezing(companyAccount.getBusinessManagerId(), company.getCompname()+"该企业三个月未交易已自动冻结。")).start();
		}
	}

	public SmartResult setAutoFreeze(BaseSimpleFormBean<SetAutoFreezeFormBean> formBean) {
		SetAutoFreezeFormBean reqdata = formBean.getReqdata();
		int compid = reqdata.getCompid();
		Company company = new Company().selectById(compid);
		Asserts.notNull(company, StatusMsg.StatusMsg_302);
		company.setAutoFreeze(reqdata.getAutoFreeze()).updateById();
		return smartResult();
	}
	//添加智合规
	public SmartResult addComplianceIntelligence(BaseSimpleFormBean<AddComplianceIntelligenceFormBean> formBean) {
		AddComplianceIntelligenceFormBean reqdata = formBean.getReqdata();
		//判断compid是否等于空
		if (reqdata.getCompid() == null || reqdata.getCompid() <= 0) return errorParamSmartResult();
		//总分
		Integer total = reqdata.getBusinessLicense()+reqdata.getIntroductionToMainBusiness()+reqdata.getRiskControlRestriction()
				+reqdata.getListedCompany()+ reqdata.getEmploymentScale()+ reqdata.getBusinessCircles()+ reqdata.getRegisteredCapital()
				+ reqdata.getFrontDeskPhotos()+ reqdata.getBillingInformation()+ reqdata.getContactInformation()
				+ reqdata.getCorporateInformation()+ reqdata.getCompanyWebsite()+ reqdata.getRequirementDescription()
				+ reqdata.getSettlementRules()+ reqdata.getFiveConsistent()
				+ reqdata.getMakerComplaints()+ reqdata.getCrowdsourcingContract()+ reqdata.getPersonnelCompliance()
				+ reqdata.getIssuingRationality()+ reqdata.getDeliverables()+ reqdata.getAuthenticityOfDeliverables()
				+ reqdata.getAcceptanceSheet()+ reqdata.getPersonnelPunchIn();
		//判断评分是否超过规定评分
//		if (reqdata.getBusinessLicense() < 20){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getIntroductionToMainBusiness() < 20){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getRiskControlRestriction() < 20){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getListedCompany() < 5){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getEmploymentScale() < 5){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getBusinessCircles() < 5){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getRegisteredCapital() < 5){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getFrontDeskPhotos() < 20){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getBillingInformation() < 10){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getContactInformation() < 10){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getCorporateInformation() < 5){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getCompanyWebsite() < 5){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getRequirementDescription() < 20){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getSettlementRules() < 20){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getFiveConsistent() < 40){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getMakerComplaints() < 10){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getCrowdsourcingContract() < 30){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getPersonnelCompliance() < 30){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getIssuingRationality() < 40){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getDeliverables() < 30){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getAuthenticityOfDeliverables() < 30){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getAcceptanceSheet() < 20){ return smartResult(StatusMsg.StatusMsg_931); }
//		if (reqdata.getPersonnelPunchIn() < 10){ return smartResult(StatusMsg.StatusMsg_931); }
		//获取企业
		ComplianceIntelligence complianceIntelligence = new ComplianceIntelligence().selectOne(Condition.create().eq("compid", reqdata.getCompid()));
		//如果compid是空就添加数据
		if (complianceIntelligence == null) {
			ComplianceIntelligence complianceIntelligences = new ComplianceIntelligence();
			BeanUtils.copyProperties(reqdata,complianceIntelligences);
			complianceIntelligences.setTotal(total);
			complianceIntelligences.insert();
			return smartResult();
		}
		//相反就修改
		BeanUtils.copyProperties(reqdata, complianceIntelligence);
		complianceIntelligence.setTotal(total);
		complianceIntelligence.updateById();
		return smartResult();
	}
	//查看智合规详情
	public SmartResult<ComplianceIntelligence> complianceDetails(BaseSimpleFormBean<Integer> formBean) {
		Integer compid = formBean.getReqdata();
		if (compid == null || compid <= 0) return errorParamSmartResult();
		ComplianceIntelligence complianceIntelligence = new ComplianceIntelligence().selectOne(Condition.create().eq("compid", compid));
		if (complianceIntelligence == null) return emptyDataSmartResult();
		return smartResult(complianceIntelligence);
	}
	//发布已经保存的草稿
	public SmartResult publishSavedDrafts(BaseSimpleFormBean<Integer> formBean) {
		Integer compid = formBean.getReqdata();
		if (compid == null || compid <= 0) return errorParamSmartResult();
		ComplianceIntelligence complianceIntelligence = new ComplianceIntelligence().selectOne(Condition.create().eq("compid", compid));
		if (complianceIntelligence == null) return emptyDataSmartResult();
		//状态改为发布
		complianceIntelligence.setPublish(1).updateById();
		return smartResult();
	}
	//获取智合规列表
	public SmartResult getComplianceList(BaseSimpleFormBean<GetComplianceListFormBean> formBean) {
		GetComplianceListFormBean reqdata = formBean.getReqdata();
		String compName = reqdata.getCompName();
		Integer whetherToScore = reqdata.getWhetherToScore();
		Integer publish= reqdata.getPublish();
		if (whetherToScore == null) {
			whetherToScore = 0;
		}
		Page<GetComplianceListDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<GetComplianceListDto> dto = complianceIntelligenceMapper.getComplianceList(compName, whetherToScore,publish);
		for (GetComplianceListDto dtos:dto){
			 dtos.setRankingProportion(complianceIntelligenceMapper.getRankingProportion(dtos.getCompid()));
		}
		return smartResultPage(page);
	}
	public SmartResult batchChangeBusiness(BaseSimpleFormBean<BatchChangeBusinessFormBean> formBean) {
		BatchChangeBusinessFormBean  reqdata = formBean.getReqdata();
		List<Integer> list = reqdata.getCompIdList();
		for (Integer compid:list) {
			CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
			Asserts.notNull(companyAccount);
			Asserts.isTrue(companyAccount.setBusinessManagerId(reqdata.getBusinessManagerId()).updateById());

			Company company = new Company().selectById(compid);
			Asserts.notNull(company, StatusMsg.StatusMsg_302);
			//如果企业对应的商务经理改变了 修改对应的客户表中的商务
			CrmCustomer crmCustomer = new CrmCustomer().selectOne(Condition.create().eq("compid", compid).eq("status", 1));
			if (null != crmCustomer && null != crmCustomer.getCustPerson()) {
				//查询到当前客户对应的负责人
				CrmSystemManager crmSystemManager = new CrmSystemManager().selectById(crmCustomer.getCustPerson());
				if (null != crmSystemManager && 0 != crmSystemManager.getBusinessManagerId()) {
					//判断当前该客户的负责人对应的商务经理和 企业编辑之后的商务经理是否一样 不一样更新当前客户的负责人(已企业为准)
					if (!crmSystemManager.getBusinessManagerId().equals(reqdata.getBusinessManagerId())) {
						CrmSystemManager nowSystemManager = new CrmSystemManager().selectOne(
								Condition.create().eq("business_manager_id", reqdata.getBusinessManagerId()).eq("state", 1));
						if (null == nowSystemManager) {
							return smartResult(StatusMsg.StatusMsg_335);
						}
						//添加商务经理变更记录
						String describe;
						//记录前负责人ID
						int frontDutyId = 0;
						if (null == crmCustomer.getCustPerson() || 0 == crmCustomer.getCustPerson()) {
							describe = "负责人由   变更为" + nowSystemManager.getManagername();
						} else {
							CrmSystemManager leader = new CrmSystemManager().selectById(crmCustomer.getCustPerson());
							if (null == leader) {
								describe = "负责人由   变更为" + nowSystemManager.getManagername();
							} else {
								frontDutyId = leader.getManagerid();
								describe = "负责人由" + leader.getManagername() + "变更为" + nowSystemManager.getManagername();
							}
							ChangeRecord changeRecord = new ChangeRecord();
							changeRecord.setCustId(crmCustomer.getCustId());
							changeRecord.setDescribe(describe);
							changeRecord.setOperatorId(formBean.getUserid());
							changeRecord.setFrontDutyId(frontDutyId);
							if (!changeRecord.insert()) {
								LogUtil.error("客户列表修改负责人-新增负责人变更记录失败！");
							}
						}
						crmCustomer.setCustPerson(nowSystemManager.getManagerid()).updateById();
						//商务经理发生变更，通知变更后的商务经理
						String info = "企业" + company.getCompname() + "的商务经理变更为您，请及时跟进。";
						new Thread(() -> {
							commonService.sendEnterpriseWeChatNotice(nowSystemManager.getBusinessManagerId(),
									nowSystemManager.getManagername(),
									1, info);
						}).start();

					}
				}
			}
		}
		return smartResult();
	}

	/**
	 * 导出未上传已过期的合同
	 */
	public void exportVerifyList(HttpServletResponse response) {
		List<CompanyVerifyBriefDto> list = companyMapper.exportVerifyList();
		String file = RandomUtil.createRandomNo("导出未上传已过期的合同", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), CompanyVerifyBriefDto.class).sheet("导出未上传已过期的合同").doWrite(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void projectAcceptance() {
		List<ProjectCompanyDto> list = companyProjectMapper.projectAcceptance();
		if(!CollectionUtils.isEmpty(list)){
			//消息
			StringBuilder message = new StringBuilder();
			message.append("以下企业有订单还未验收:");
			for (ProjectCompanyDto dto:list){
				//发送消息给企业
				wxMessageService.enterpriseProjectAcceptanceNotice(dto);
				message.append(dto.getCompname()+"公司有"+dto.getQuantity()+"笔,顾问:"+dto.getBusinessManager()+";");
			}
			//发送消息给夏伦聪
			wxMessageService.sendTina(message);
			//通知胡刚
			new Thread(() -> commonService.enterpriseAutomaticFreezing(28, message.toString())).start();
		}
	}

	public SmartResult<QuantityOfDeliverablesDto> quantityOfDeliverables(BaseSimpleFormBean<Integer> formBean) {
		QuantityOfDeliverablesDto quantityOfDeliverablesDto = new QuantityOfDeliverablesDto();
		//总已完成项目数量
		int numberOfProjectsCompleted =
				companyProjectMapper.getZddProjectNum(formBean.getReqdata()," ") +
				crowdsourceProjectMapper.getCroProjectNum(formBean.getReqdata()," ");
		//交付物
		int deliverables =
				companyProjectMapper.getZddProjectNum(formBean.getReqdata()," AND (cp.attachment_url IS NOT NULL or cp.attachment_url != '') ") +
				crowdsourceProjectMapper.getCroProjectNum(formBean.getReqdata()," AND (cp.project_file_url IS NOT NULL or cp.project_file_url != '') ");
		//验收单
		int receipt =
				companyProjectMapper.getZddProjectNum(formBean.getReqdata()," AND (cp.delivery_path IS NOT NULL or cp.delivery_path!= '') ") +
				crowdsourceProjectMapper.getCroProjectNum(formBean.getReqdata()," AND (cp.delivery_path IS NOT NULL or cp.delivery_path!= '') ");
		//交付物/验收单
		int deliveryReceipt =
				companyProjectMapper.getZddProjectNum(formBean.getReqdata(),"AND ((cp.attachment_url IS NOT NULL and cp.attachment_url != '' ) or cp.delivery_path IS NOT NULL) ") +
				crowdsourceProjectMapper.getCroProjectNum(formBean.getReqdata(),"AND (cp.project_file_url IS NOT NULL or cp.delivery_path IS NOT NULL) ");

		quantityOfDeliverablesDto.setNumberOfProjectsCompleted(numberOfProjectsCompleted);
		quantityOfDeliverablesDto.setDeliverables(deliverables);
		quantityOfDeliverablesDto.setReceipt(receipt);
		quantityOfDeliverablesDto.setDeliveryReceipt(deliveryReceipt);
		return smartResult(quantityOfDeliverablesDto);
	}
	public SmartResult setUpALimitedLiabilityCompany(BaseSimpleFormBean<SetAutoFreezeFormBean> formBean) {
		SetAutoFreezeFormBean reqdata = formBean.getReqdata();
		int compid = reqdata.getCompid();
		Company company = new Company().selectById(compid);
		Asserts.notNull(company, StatusMsg.StatusMsg_302);
		company.setLimitedLiabilityCompany(reqdata.getLimitedLiabilityCompany()).updateById();
		return smartResult();
	}
	public SmartResult liabilityQueryCompany(BaseSimpleFormBean<String> formBean) {
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CompanyBriefDto> list = companyMapper.liabilityQueryCompany(formBean.getReqdata());
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public SmartResult checkSameLabelCompanyRate(BaseSimpleFormBean<CheckSameLabelCompanyBean> formBean) {
		AccountLinkLabel accountLinkLabel = new AccountLinkLabel().selectById(formBean.getReqdata().getAccountLinkId());
		Asserts.notNull(accountLinkLabel, StatusMsg.StatusMsg_102);
		List<SameLabelVO> resultList = new ArrayList<>();

		//企业标签类型
		if (accountLinkLabel.getType() == 1) {
			// 获取所有设置该标签的企业
			List<CompanyLabelDto> list = companyAccountMapper.getCompanyAccountList(formBean.getReqdata().getCompid(), accountLinkLabel.getId());
			if (CollectionUtils.isEmpty(list)) {
				return smartResult();
			}
			// 获取标准企业
			Map<Integer, List<CompanyLabelDto>> map = list.stream().collect(Collectors.groupingBy(CompanyLabelDto::getCompid));
			List temp = map.get(formBean.getReqdata().getCompid());
			if (CollectionUtils.isEmpty(list) || CollectionUtils.isEmpty(temp) || temp.size() < 1) {
				return smartResult(StatusMsg.StatusMsg_302);
			}
			CompanyLabelDto compStandard = map.get(formBean.getReqdata().getCompid()).get(0);
			// 获取标准企业的创客信息
			List<MakerStudio> makerStandardList = makerStudioMapper.getCompMakerStudio(compStandard.getCompid());
			// 获取标准企业的合伙人信息
			List<PartnerAndCompanyRelationshipDto> partnerStandardList = partnerCompanyMapper.getPartnerCompanyByCompId(compStandard.getCompid());

			for (CompanyLabelDto cld : list) {
				// 开启了 业务，且关闭了企业费率，比较创客费率
				if (cld.getOpenZdd() && compStandard.getOpenZdd() && NumberUtil.equals(cld.getCompanyTaxFlag(), 0) && NumberUtil.equals(cld.getCompanyTaxFlag(), compStandard.getCompanyTaxFlag())) {
					// 比较这两个企业下面的所有创客税率
					List<MakerStudio> makerList = new ArrayList<>();
					if (cld.getCompid().equals(compStandard.getCompid())) {
						makerList.addAll(makerStandardList);
					} else {
						makerList.addAll(makerStudioMapper.getCompMakerStudio(cld.getCompid()));
					}
					if (makerList.size() >= 1) {
						// 取一个创客作为标准比较
						MakerStudio makerStandard = CollectionUtils.isEmpty(makerStandardList) ? makerList.get(0) : makerStandardList.get(0);
						for (MakerStudio ms : makerList) {
							if(ms.getUserid().equals(makerStandard.getUserid())) continue;
							if(!ms.getGenLowServiceRate().equals(makerStandard.getGenLowServiceRate())
									|| !ms.getGenHighTaxRate().equals(makerStandard.getGenHighTaxRate()) || !ms.getGenHighServiceRate().equals(makerStandard.getGenHighServiceRate())
									|| !ms.getSpeTaxRate().equals(makerStandard.getSpeTaxRate()) || !ms.getSpeServiceRate().equals(makerStandard.getSpeServiceRate())
									|| !ms.getYearlyHighTaxRate().equals(makerStandard.getYearlyHighTaxRate()) || !ms.getYearlyHighServiceRate().equals(makerStandard.getYearlyHighServiceRate())
									|| !ms.getYearlyHigh2TaxRate().equals(makerStandard.getYearlyHigh2TaxRate()) || !ms.getYearlyHigh2ServiceRate().equals(makerStandard.getYearlyHigh2ServiceRate())
									|| !ms.getYearlyHigh3TaxRate().equals(makerStandard.getYearlyHigh3TaxRate()) || !ms.getYearlyHigh3ServiceRate().equals(makerStandard.getYearlyHigh3ServiceRate())
									|| !ms.getFixedServiceRate().equals(makerStandard.getFixedServiceRate())	|| !ms.getFixedService().equals(makerStandard.getFixedService())) {
								SameLabelVO vo = new SameLabelVO().setCompname(cld.getCompname()).setType(4).setUserType(2).setUserName(ms.getUsername());
								resultList.add(vo);
							}
						}
					}
				}

				// 校验企业信息
				// a、企业开启了 业务，则比较 费率是否一致，不开启的不比较
				//a1、未开启企业费率就对比创客费率
				//a2、开启了企业费率就对比企业费率，不需要再对比创客费率
				//b、开启了智众包业务 比较智众包费率是否一致
				//c、开启了智零工业务 比较智零工费率是否一致
				if (cld.getOpenZdd() && compStandard.getOpenZdd() && !NumberUtil.equals(cld.getCompid(),compStandard.getCompid()) && !NumberUtil.equals(cld.getCompanyTaxFlag(), compStandard.getCompanyTaxFlag())) {
					SameLabelVO vo = new SameLabelVO().setCompname(cld.getCompname()).setType(2).setUserType(1).setUserName(cld.getCompname());
					resultList.add(vo);
				}
				if (!NumberUtil.equals(cld.getCompid(), compStandard.getCompid()) && NumberUtil.equals(cld.getCompanyTaxFlag(), 1) && NumberUtil.equals(cld.getCompanyTaxFlag(), compStandard.getCompanyTaxFlag())) {
					if (!cld.getGenLowServiceRate().equals(compStandard.getGenLowServiceRate())
							|| !cld.getGenHighServiceRate().equals(compStandard.getGenHighServiceRate()) || !cld.getGenHighTaxRate().equals(compStandard.getGenHighTaxRate())
							|| !cld.getSpeServiceRate().equals(compStandard.getSpeServiceRate()) || !cld.getSpeTaxRate().equals(compStandard.getSpeTaxRate())
							|| !cld.getYearlyHighServiceRate().equals(compStandard.getYearlyHighServiceRate()) || !cld.getYearlyHighTaxRate().equals(compStandard.getYearlyHighTaxRate())
							|| !cld.getYearlyHigh2ServiceRate().equals(compStandard.getYearlyHigh2ServiceRate()) || !cld.getYearlyHigh2TaxRate().equals(compStandard.getYearlyHigh2TaxRate())
							|| !cld.getYearlyHigh3ServiceRate().equals(compStandard.getYearlyHigh3ServiceRate()) || !cld.getYearlyHigh3TaxRate().equals(compStandard.getYearlyHigh3TaxRate())
							|| !cld.getFixedService().equals(compStandard.getFixedService()) || !cld.getFixedServiceRate().equals(compStandard.getFixedServiceRate())) {
						SameLabelVO vo = new SameLabelVO().setCompname(cld.getCompname()).setType(3).setUserType(1).setUserName(cld.getCompname());
						resultList.add(vo);
					}
				}

				//智众包开启 则比较费率是否一致
				if (!NumberUtil.equals(cld.getCompid(), compStandard.getCompid()) && NumberUtil.equals(cld.getIntelCrowdsource(), 2) && NumberUtil.equals(cld.getIntelCrowdsource(), compStandard.getIntelCrowdsource())) {
					if (!cld.getProjectServiceRate().equals(compStandard.getProjectServiceRate())
							||!cld.getLowTaxRate().equals(compStandard.getLowTaxRate())
							||!cld.getHighTaxRate().equals(compStandard.getHighTaxRate())
							|| !cld.getBaseTaxRate().equals(compStandard.getBaseTaxRate())) {
						SameLabelVO vo = new SameLabelVO().setCompname(cld.getCompname()).setType(5).setUserType(1).setUserName(cld.getCompname());
						resultList.add(vo);
					}
				}

				//智零工开启 比较费率是否一致
				if (!NumberUtil.equals(cld.getCompid(), compStandard.getCompid()) && NumberUtil.equals(cld.getOpenOddJob(), 1) && NumberUtil.equals(cld.getOpenOddJob(), compStandard.getOpenOddJob())) {
					if (!cld.getBaseTaxRateOdd().equals(compStandard.getBaseTaxRateOdd())) {
						SameLabelVO vo = new SameLabelVO().setCompname(cld.getCompname()).setType(6).setUserType(1).setUserName(cld.getCompname());
						resultList.add(vo);
					}
				}
				// 合伙人设置不一致
				List<PartnerAndCompanyRelationshipDto> partnerList = new ArrayList<>();
				if(NumberUtil.equals(cld.getCompid(), compStandard.getCompid())) {
					partnerList.addAll(partnerStandardList);
				} else {
					List<PartnerAndCompanyRelationshipDto> partnerCldList = partnerCompanyMapper.getPartnerCompanyByCompId(cld.getCompid());
					// 有的企业有合伙人，有的企业没有合伙人，算作不一致
					if((CollectionUtils.isEmpty(partnerStandardList) && !CollectionUtils.isEmpty(partnerCldList))
						|| (!CollectionUtils.isEmpty(partnerStandardList) && CollectionUtils.isEmpty(partnerCldList))) {
						SameLabelVO vo = new SameLabelVO().setCompname(cld.getCompname()).setType(7).setUserType(1).setUserName(cld.getCompname());
						resultList.add(vo);
					}
					partnerList.addAll(partnerCldList);
				}
				if (partnerList.size() > 1) {
					// 取企业的第一个合伙人数据作为标准比较
					PartnerAndCompanyRelationshipDto partnerStandard = partnerStandardList.get(0);
					for (PartnerAndCompanyRelationshipDto pd : partnerList){
						if(!NumberUtil.equals(pd.getRatio(),partnerStandard.getRatio())
								|| !NumberUtil.equals(pd.getState(),partnerStandard.getState())
								|| !NumberUtil.equals(pd.getType(),partnerStandard.getType())) {
							SameLabelVO vo = new SameLabelVO().setCompname(cld.getCompname()).setType(7).setUserType(3).setUserName(pd.getRealname());
							resultList.add(vo);
						}
					}
				}
			}

			Map<String,List<SameLabelVO>> mapResult = resultList.stream().collect(Collectors.groupingBy(SameLabelVO::getCompname));
			return smartResult().setList(Arrays.asList(mapResult)).setObject(compStandard);
		}

		return smartResult();
	}

	public SmartResult queryCompanyByAccountLinkId(BaseSimpleFormBean<Integer> formBean) {
		Page<Company> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<Company> list = companyMapper.queryCompanyByAccountLinkId(formBean.getReqdata());
		return smartResultPage(page);
	}

	public SmartResult getAnEnterpriseContract(BaseSimpleFormBean<GetAnEnterpriseContractBean> formBean) {
		Page<GetAnEnterpriseContractDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<GetAnEnterpriseContractDto> list = companyMapper.getAnEnterpriseContract(formBean.getReqdata().getCompname(),formBean.getReqdata().getState());
		for (GetAnEnterpriseContractDto dto:list){
			List<CompanyEntrustFile> fileList = companyEntrustFileMapper.getAnEnterpriseContract(dto.getCompid());
			dto.setListOfContracts(fileList);
		}
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public void whetherTheContractHasExpired() {
		List<Company> list = companyMapper.whetherTheContractHasExpired();
		for (Company dto:list){
			List<CompanyEntrustFile> fileList = companyEntrustFileMapper.getAnEnterpriseContract(dto.getCompid());
			dto.setContractStatus(0);
			if (CollectionUtils.isEmpty(fileList)){
				dto.setContractStatus(1);
			}else {
				for (CompanyEntrustFile entrustFile:fileList){
					if (entrustFile.getState() == 1){
						dto.setContractStatus(3);
						break;
					}
				}
			}
			if (dto.getContractStatus() == 0){
				dto.setContractStatus(2);
			}
			companyMapper.updateById(dto);
		}
	}
}
